0

If I have 2 arrays:

arr1: ["1","2"]
arr2: [{id: 1, color: "green"}, {id: 2, color: "yellow"}, {id: 3, color: "red"}]

And I want to obtain:

result: [{id: 1, color: "green"}, {id: 2, color: "yellow"}]

I am trying with

arr2.filter(
  e => arr1.indexOf(e.id) !== -1
);

But result is empty.

3 Answers 3

2

The problem with your code is that as your inputs have different types(id is a number but arr1 has strings), this arr1.indexOf(e.id) !== -1 will always be false.

Convert one of them to a number like this:

const arr1 = ["1","2"]
const arr2 = [{id: 1, color: "green"}, {id: 2, color: "yellow"}, {id: 3, color: "red"}]

const result = arr2.filter(el => arr1.some(aEl => el.id === +aEl))
console.log(result)

Alternatively, you can convert the ids to strings and use your existing code:

const arr1 = ["1", "2"],
  arr2 = [{
    id: 1,
    color: "green"
  }, {
    id: 2,
    color: "yellow"
  }, {
    id: 3,
    color: "red"
  }],

  result = arr2.filter(
    e => arr1.indexOf(e.id.toString()) !== -1
  );

console.log(result)

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

Comments

2

You could use Array.prototype.filter() with Array.prototype.some() method to get the result.

const arr1 = ['1', '2'];
const arr2 = [
  { id: 1, color: 'green' },
  { id: 2, color: 'yellow' },
  { id: 3, color: 'red' },
];

const ret = arr2.filter((x) => arr1.some((y) => +y === x.id));
console.log(ret);

Another solution using Set Object.

const arr1 = ['1', '2'];
const arr2 = [
  { id: 1, color: 'green' },
  { id: 2, color: 'yellow' },
  { id: 3, color: 'red' },
];
const set = new Set(arr1);
const ret = arr2.filter((x) => set.has(x.id.toString()));
console.log(ret);

Comments

0

Another solution is may be with .includes() method.

const arr1 =  ["1","2"]
const arr2 = [{id: 1, color: "green"}, {id: 2, color: "yellow"}, {id: 3, color: "red"}]

const result = arr2.filter(n => arr1.includes(String(n.id)));
console.log(result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.