Saturday, June 1, 2024
 Popular · Latest · Hot · Upcoming
130
rated 0 times [  132] [ 2]  / answers: 1 / hits: 15338  / 6 Years ago, fri, april 6, 2018, 12:00:00

How is this working? I am having a hard time understand this.





const arr1 = [{id:1,name:jhon},{id:2,name:max},{id:3,name:fer}];

const arr2 = [8, 9];
var diffArray = arr2.filter(x => !arr1.filter(y => y.id === x).length);
console.log(diffArray);




More From » javascript

 Answers
26

From MDN The filter() method creates a new array with all elements that pass the test implemented by the provided function.
Code x => some_code is called an arrow function and can be translated to: function(x) {return some_code}
Basically what is done here is that arr2.filter() will return all elements of said arr2 that pass the condition. Condition here is, that the length of filtered arr1 must be zero (meaning, that the match was not found). Length of array as numerical value can be used as true/false and can be negated with !. That's whats going on here:



arr1.filter(y => y.id === x)          // means, give me elements of arr1, that are the same as in array 2
arr1.filter(y => y.id === x).length // means, the length of said array of elements
!arr1.filter(y => y.id === x).length // means, if length == 0 make it true and if more than 0 -> make it false

[#54738] Wednesday, April 4, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
anitadevonm

Total Points: 730
Total Questions: 93
Total Answers: 74

Location: Estonia
Member since Wed, Jun 8, 2022
2 Years ago
;