I'm new in JavaScript programming and I have two object arrays that have the following structure:
myFirstObjArray = [{foo: 1, bar: 1}, {foo: 3, bar: 3}, {foo: 4, bar: 5}]; mySecondObjArray = [{foo: 2}, {foo: 4}, {foo: 5}];
I need to get two separate arrays containing the values of key foo
, the first containing the ones that are in the first array but not in the second, based on the value of key foo
, and the second that are in mySecondObjArray
but not in myFirstObjArray
.
Is there a way to do this without
for(i=0;i<myFirstObjArray.length;i++) for(j=0;j<mySecondObjArray .length;j++) {...build first array here} for(i=0;i<mySecondObjArray .length;i++) for(j=0;j<myFirstObjArray.length;j++) {...build second array here}
? Perhaps my question is a duplicate one that I didn't find, so please be gentle.
Expected output:
firstArray = [{foo: 1}, {foo: 3}]; secondArray = [{foo: 2}, {foo: 5}];
Use the . filter() method on the first array and check if the elements of first array are not present in the second array, Include those elements in the output.
Use the inbuilt ES6 function some() to iterate through each and every element of first array and to test the array. Use the inbuilt function includes() with second array to check if element exist in the first array or not. If element exist then return true else return false.
Javascript array contains another array To check if the array contains an array in Javascript, use array some(), and array includes() function. The array some() method checks each element against a test method and returns true if any array item passes the test function.
To remove elements contained in another array, we can use a combination of the array filter() method and the Set() constructor function in JavaScript.
You can simply filter one array's elements by setting the condition based on other array's elements like.
var myFirstObjArray = [{foo: 1, bar: 1}, {foo: 3, bar: 3}, {foo: 4, bar: 5}], mySecondObjArray = [{foo: 2}, {foo: 4}, {foo: 5}], firstArray = myFirstObjArray.filter(o=> !mySecondObjArray.some(i=> i.foo === o.foo)); secondArray = mySecondObjArray.filter(o=> !myFirstObjArray.some(i=> i.foo === o.foo)); console.log(firstArray.map(o=> {return {'foo' : o.foo}})) console.log(secondArray.map(o=> {return {'foo' : o.foo}}))
Ps:
The some()
method tests whether at least one element in the array passes the test implemented by the provided function. And I've added a function which just checks if foo
property exists in the other array with the same value to be able to filter from the first array.
At the end you can use .map
to filter out the desired key value pairs
Hope that makes sense
Read more about .some
and filter
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