-2

I have the 2 below lists:

array_main = [[01-0158969,315],[01-0161045,699],[01-0161046,500]]
array_helper_both = [[01-0158969,315],[01-0161045,699],[01-0161050,500]]

I am trying to compare array_main with array_helper_both and if there are any differences (elements PRESENT in array_main but not in array_helper_both), then I am trying to add it to array_helper_both. For example, "01-0161046" is in array_main but not in array_helper_both.

Hence array_helper_both result would be:

[[01-0158969,315],[01-0161045,699],[01-0161050,500],[01-0161046,500]]

This is the code I tried but doesn't seem to work:

var list3 = array_helper_both.filter(x => !array_main.includes(x));
var list4 = array_helper_both.concat(array_main.filter(x => !array_helper_both.includes(x)));

Any leads/suggestions would be appreciated.

user3447653
  • 3,968
  • 12
  • 58
  • 100

2 Answers2

0

This is would work if they were flat arrays. But they are 2D-arrays. You can't compare two 2D-arrays as if they are just 1D-array and some values if (some_array.includes(some_value)).

Probably you could in this case turn the inner arays into flat strings:

[01-0158969,315] --> "01-0158969,315"

To compare the values, and then turn the values back into arrays:

"01-0158969,315" --> [01-0158969,315]

Yuri Khristich
  • 13,448
  • 2
  • 8
  • 23
0

You have to compare two arrays (elements in array_main and in array_help_both). The simplest option would be to use JSON.stringify():

var array_helper_both_string = array_helper_both.map(val => JSON.stringify(val));
var list4 = array_helper_both.concat(array_main.filter(x => !array_helper_both_string.includes(JSON.stringify(x))));

See the following thread for possible (and probably better) alternatives:

Iamblichus
  • 18,540
  • 2
  • 11
  • 27