0

Let say I have two arrays

From here I want to filter arr1 with arr2 condition (assuming arr2 = arr1 id). I have tried this code but only return first condition.

const arr1 = [{
    id: 1,
    name: "Jhon"
  },
  {
    id: 2,
    name: "Barbara"
  },
  {
    id: 3,
    name: "Rio"
  }
];
const arr2 = [1, 2, 5];


const filter = (arr1, arr2) => {
  const output = arr1.filter(value => {
    for (let i = 0; i < arr2.length; i++) {
      if (value.id !== arr2[i]) {
        return false;
      }
      return true;
    }
  })
  console.log(output);
};

filter(arr1, arr2);
// output = [{id: 1, name: "Jhon"}]
// intended output [{id: 1, name: "Jhon"}, {id: 2, name: "Barbara}]

Anyone can tell me what I'm missing? Thank you

1
  • Your return true; is inside the for loop body, so it runs on the first loop iteration if value.id !== arr2[i] is false. Move it after the for loop so you only return false; when none of the entries matched. Or you can use some: .filter(value => arr2.some(v => v === value.id)) Commented Mar 2, 2021 at 13:24

1 Answer 1

0

See the dupe why it did not work and then vastly simplify this

const arr1 = [{ id: 1, name: "Jhon" }, { id: 2, name: "Barbara" }, { id: 3, name: "Rio" } ];
const arr2 = [1, 2, 5];

const filter = (arr1, arr2) => arr1.filter(({id}) => arr2.includes(id))

console.log(filter(arr1,arr2))

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

2 Comments

Heh, I had the arrays backward in my mind, hence reaching for some instead of includes in my comment.
@T.J.Crowder I was wondering. A bit like a woman we know who sees everything as a reduce

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.