0

In Javascript we have an array:

let arr1 = [1, 2, 3, 4, 5];

...and an array of objects:

let arr2 = [ {name: "banana", id: 1},
             {name: "mango", id: 3} ];

I want to remove all the elements from arr1 where arr2's id = arr1's value and return an array like this:

[2, 4, 5]

Here is what I've tried, but it doesn't seem to work.

let newArr = arr1.filter(
    x => !arr2.includes(e => e.id === x)
)

How can I achieve this? I can use lodash as well as ES6.

1
  • 1
    What is your attempt ? Commented Apr 19, 2020 at 12:45

3 Answers 3

3

The .includes() method doesn't allow you to pass a method into it to define equality. You can use .some() instead, which does allow you to specify this:

const arr1 = [1, 2, 3, 4, 5];
const arr2 = [
  {name: "banana", id: 1},
  {name: "mango", id: 3}
];

const newArr = arr1.filter(x => !arr2.some(e => e.id === x))
console.log(newArr);

A more efficient approach would be to grab all the id properties from the objects in your array and put then in a Set for quick look-up. Then use .filter() with .has() like so:

const arr1 = [1, 2, 3, 4, 5];
const arr2 = [
  {name: "banana", id: 1},
  {name: "mango", id: 3}
];

const idSet = new Set(arr2.map(({id}) => id));
const newArr = arr1.filter(x => !idSet.has(x))
console.log(newArr);

Sign up to request clarification or add additional context in comments.

Comments

3

You can first create a temporary of id and age, then use filter() with includes()

let arr1 = [1, 2, 3, 4, 5];
let arr2 = [ {name: "banana", id: 1},
         {name: "mango", age: 3} ];
let temp = arr2.map(i => i.id || i.age);
let res = arr1.filter(i => !temp.includes(i));
console.log(res);

Comments

1
let arr1 = [1, 2, 3, 4, 5];

let arr2 = [ {name: "banana", id: 1},
             {name: "mango", id: 3} ];

arr1.map((item,index) => 
  arr2.map(object => {
    if(item == object.id) arr1.splice(index,1)
  })
)

console.warn(arr1) /// output [2, 4, 5]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.