I have two arrays in javascript -:
var array1 = ['12','1','10','19','100']; var array2 = ['12','10','19'];
I need to a method to get the unique from two arrays and put them in array3 Array3
should be -:
var array3 = ['1','100'];
Thanks for help.
The concat() method concatenates (joins) two or more arrays. The concat() method returns a new array, containing the joined arrays. The concat() method does not change the existing arrays.
var array3 = array1.filter(function(obj) { return array2.indexOf(obj) == -1; });
MDN on Array#filter: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter
Includes a polyfill for older browsers.
With a bit of ES6 magic it can be fairly concise. Note that we need to check both ways around in case there are unique items in either array.
const arr1 = [1, 2, 3, 4, 5]; const arr2 = [1, 3, 8]; let unique1 = arr1.filter((o) => arr2.indexOf(o) === -1); let unique2 = arr2.filter((o) => arr1.indexOf(o) === -1); const unique = unique1.concat(unique2); console.log(unique); // >> [2, 4, 5, 8]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With