skip to Main Content

How can I get the indices where array entries match a particular condition?

Say, want to match device = ‘1’…

[
    { device: '1', type: 'a' },
    { device: '2', type: 'b' },
    { device: '3', type: 'c' },
    { device: '1', type: 'd' }
]

The returned result should be array [0,3].

Does JavaScript have a findIndexAll() or something like that?

2

Answers


  1. You can create a function to do this using a combination of "map" and "indexOf", like this:

    function findIndexesByProperty(array, property, value) {
      return array.map((item, index) => item[property] === value ? index : -1)
        .filter(index => index !== -1);
    }
    
    const data = [{
        device: '1',
        type: 'a'
      },
      {
        device: '2',
        type: 'b'
      },
      {
        device: '3',
        type: 'c'
      },
      {
        device: '1',
        type: 'd'
      },
    ];
    
    const indexes = findIndexesByProperty(data, 'device', '1');
    console.log(indexes); // Output: [0, 3]
    Login or Signup to reply.
  2. You can use reduce to push the indices of the matching entries into an accumulator array:

    const arr = [
        { device: '1', type: 'a' },
        { device: '2', type: 'b' },
        { device: '3', type: 'c' },
        { device: '1', type: 'd' }
    ]
    
    const r = arr.reduce((a,c,i) => (c.device==='1' && a.push(i), a), [])
    
    console.log(r)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search