Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq JS join syntax

I am trying to join an array of dates and values to an array of dates, without filtering out the extra dates. The LinqJS reference here is pretty confusing on how I would actually go about using the join. The question here did not help much either.

Edit:

Join documentation here: https://svschmidt.github.io/linqjs/Collection.html#Join

It looks like I need help sorting out how to get the join to be an outer and not an inner join so it includes null/undefined values.

Say I have two arrays:

Array 1:

[
'2017-02-10',
'2017-02-11',
'2017-02-12',
'2017-02-13',
'2017-02-20',
'2017-02-21',
'2017-02-22',
'2017-02-23',
'2017-02-24',
'2017-02-25',
'2017-02-26',
'2017-02-27'
]

Array 2:

[
  { date: '2017-02-10', value:  5 },
  { date: '2017-02-12', value:  8 },
  { date: '2017-02-13', value: 13 },
  { date: '2017-02-21', value: 14 },
  { date: '2017-02-24', value: 11 },
  { date: '2017-02-27', value:  7 }
]

I want to join them so I get this as my result (- for undefined):

[
'5',
-,
'8',
'13',
-,
'14',
-,
-,
'11',
-,
-,
'7'
]

My current syntax:

Enumerable.from(array1).join(array2, '$', '$.date', "outer, inner => inner.value").toArray()

This results in an array of the values, but the results are still inner joined, and it filters out what might be the null/undefined items.

How can I do this? How does the join syntax work for LinqJS?

like image 708
Douglas Gaskell Avatar asked Jul 06 '26 05:07

Douglas Gaskell


1 Answers

I'm not sure about LinqJS, but regular JS is more than capable of doing this.

There are a couple ways to go about it. The reduce(), map(), and sort() functions are very Linq-esque and work well natively. (There is also filter() and a number of others).

const dates = [
'2017-02-10',
'2017-02-11',
'2017-02-12',
'2017-02-13',
'2017-02-20',
'2017-02-21',
'2017-02-22',
'2017-02-23',
'2017-02-24',
'2017-02-25',
'2017-02-26',
'2017-02-27'
]

const data = [
  { date: '2017-02-10', value:  5 },
  { date: '2017-02-12', value:  8 },
  { date: '2017-02-13', value: 13 },
  { date: '2017-02-21', value: 14 },
  { date: '2017-02-24', value: 11 },
  { date: '2017-02-27', value:  7 }
];

const result = dates
  .map(date => ({ date, value: '-' }))
  .concat(data)
  .filter(({ date, value }) => !(data.find(d => d.date === date) && value === '-'))
  .sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime());

console.log(result);

const justValues = Object.keys(result).map(key => result[key].value);

console.log(justValues);
like image 152
samanime Avatar answered Jul 07 '26 19:07

samanime



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!