0

I'm trying to check for condition where carId in one array is equal to id of another array.

Below is the code snippet.

const arr1 = [{
    id: '1',
    type: 'car',
    name: 'BMW',
  },
  {
    id: '2',
    type: 'car',
    name: 'Audi',
  },
  {
    id: '3',
    type: 'car',
    name: 'Benz',
  }
];

const arr2 = [{
  carId: '1'
}, {
  carId: '3'
}];

const result = arr2.map(val => arr2.find(val.carId === id))
console.log(result)

The result that I'm expecting is

[{
    id: '1',
    type: 'car',
    name: 'BMW',
  },
  {
    id: '3',
    type: 'car',
    name: 'Benz',
  }
];

Could anyone please help?

1
  • You want to do result = arr1.filter. Remember filter expects a boolean so just ensure you compare the return value of find with !== undefined. Commented Jul 9, 2020 at 2:08

3 Answers 3

2

While you should use .filter() on arr1, and pass a callback to .find(), I'd probably first convert arr2 to a simple list of IDs and use .includes() instead.

const arr1 = [{
    id: '1',
    type: 'car',
    name: 'BMW',
  },
  {
    id: '2',
    type: 'car',
    name: 'Audi',
  },
  {
    id: '3',
    type: 'car',
    name: 'Benz',
  }
];

const arr2 = [{
  carId: '1'
}, {
  carId: '3'
}];

const ids = arr2.map(o => o.carId);

const result = arr1.filter(val => ids.includes(val.id))
console.log(result)


or better yet, convert arr2 to a Set.

const arr1 = [{
    id: '1',
    type: 'car',
    name: 'BMW',
  },
  {
    id: '2',
    type: 'car',
    name: 'Audi',
  },
  {
    id: '3',
    type: 'car',
    name: 'Benz',
  }
];

const arr2 = [{
  carId: '1'
}, {
  carId: '3'
}];

const ids = arr2.map(o => o.carId);
const idSet = new Set(ids);

const result = arr1.filter(val => idSet.has(val.id))
console.log(result)

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

Comments

1

const arr1 = [{
    id: '1',
    type: 'car',
    name: 'BMW',
  },
  {
    id: '2',
    type: 'car',
    name: 'Audi',
  },
  {
    id: '3',
    type: 'car',
    name: 'Benz',
  }
];

const arr2 = [{
  carId: '1'
}, {
  carId: '3'
}];

const result = arr1.filter(a1val => arr2.find(a2val => a2val.carId === a1val.id) !== undefined);
console.log(result);

Comments

0

This might work

const result = arr2.map(val => arr1.find(item => item.id === val.carId))

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.