2

I have an array of objects and trying to extract the objects with a matched value of the array.

const A = [{_id: 'a', name: '1'}, {_id: 'b', name: '2'}, {_id: 'c', name: '3'}] and const B = ['2', '3'] So, I want to match values of Array B to the Array A and get the objects into the Array C like const C = [{_id: 'b', name: '2'}, {_id: 'c', name: '3'}]

  const C = A.forEach((list) => {
    let key = []
    if(list.includes[B]) {
    key.push(list)
     }
  })

I am stuck at here, how can I push those objects to the Array C?

3 Answers 3

1

You could filter the array.

const
    arrA = [{ _id: 'a', name: '1' }, { _id: 'b', name: '2' }, { _id: 'c', name: '3' }];
    arrB = ['2', '3'];
    arrC = arrA.filter(({ name }) => arrB.includes(name));

console.log(arrC);

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

Comments

1

when you say matched value, it seems as if you're trying too match the name value.. if that's the case- this shoould work..

const A = [{_id: 'a', name: '1'}, 
           {_id: 'b', name: '2'}, 
           {_id: 'c', name: '3'}];
const B = ['2', '3'];
const C = [];
A.forEach((item) => {
    if(B.filter(x=>x == item.name).length > 0) {
        C.push(item)
    }    
});

Comments

1

I hope I have been helpful

const arrA = [{ _id: 'a', name: '1' }, { _id: 'b', name: '2' }, { _id: 'c', name: '3' }];
const arrB = ['2', '3'];
var arrC = [];

arrB.forEach(element => {
    arrA.forEach(element2 => {
        if (element === element2.name) {
            arrC.push(element2)
        } 
    });
});

console.log(arrC);

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.