Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Merge two dimensional array with unique result

I have this two array in Javascript

var array1 = [
              ["Tech & Digital", 124],
              ["Stationery", 100]
             ]
var array2 = [
              ["Gift Item", 125],
              ["Stationery", 100]
             ]

I want to merge this 2 array with unique value as follows,

            [
              ["Tech & Digital", 124],
              ["Stationery", 100],
              ["Gift Item", 125]
             ]

I tried concat function, but it's not working as expected.

like image 385
iLaYa ツ Avatar asked Feb 10 '26 22:02

iLaYa ツ


1 Answers

Are you using nested arrays to emulate an object that preserves order? If so, then write a container object that handles the sorting for you.

If not, you can use Underscore or Lo-Dash:

_.uniq(_.union(array1, array2), false, JSON.stringify)

Since [1] != [1], you have to compare them manually. JSON.stringify is one (hacky) way of doing it.

like image 79
Blender Avatar answered Feb 13 '26 13:02

Blender



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!