Find all matching elements with in an array of objects

Use array filter method. Like

arr.filter(res => res.arrayWithvalue.indexOf('4') !== -1);

Two things: first, Array.find() returns the first matching element, undefined if it finds nothing. Array.filter returns a new array containing all matching elements, [] if it matches nothing.

Second thing, if you want to match 4,5, you have to look into the string instead of making a strict comparison. To make that happen we use indexOf which is returning the position of the matching string, or -1 if it matches nothing.


Example:

const arr = [
  {
    name: 'string 1',
    arrayWithvalue: '1,2',
    other: 'that',
  },
  {
    name: 'string 2',
    arrayWithvalue: '2',
    other: 'that',
  },
  {
    name: 'string 2',
    arrayWithvalue: '2,3',
    other: 'that',
  },
  {
    name: 'string 2',
    arrayWithvalue: '4,5',
    other: 'that',
  },
  {
    name: 'string 2',
    arrayWithvalue: '4',
    other: 'that',
  },
];

const items = arr.filter(item => item.arrayWithvalue.indexOf('4') !== -1);

console.log(items);