Rohan Singh
Rohan Singh

Reputation: 91

ES5 filter inside filter

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);

Upvotes: 1

Views: 15776

Answers (3)

Buzzeins
Buzzeins

Reputation: 101

Or even shorter ;)

let diffArray = arr2.filter(x => arr1.filter(y => y.id === x).length > 0 ? false : true)

Upvotes: 0

Satish Kumar
Satish Kumar

Reputation: 601

Simplified,

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

const arr2 = [8, 9];

var diffArray = arr2.filter(x => {
  let elementsOfArray2PresentInArray1 = arr1.filter(y => {
    return y.id === x
  });

  if (elementsOfArray2PresentInArray1.length > 0) {
    return false
  } else {
    return true;
  }
  //`return !length;` will  return false if length > 0
});

console.log(diffArray)

Upvotes: 4

Ludovit Mydla
Ludovit Mydla

Reputation: 822

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

Upvotes: 2

Related Questions