Igor Simic
4 years ago

Angular - how to find array item by item value


How to find array item based on item value in Angular? Answer: by using .filter(). How to find index of array element based on property value? Answer: by using .findIndex().
Here is the example:

So, lets say that we have a list of data array, and we want to find array item based on property value:
data = [
  {
    srcUrl: 'https://preview.ibb.co/jrsA6R/img12.jpg',
    previewUrl: 'https://preview.ibb.co/jrsA6R/img12.jpg'
  },
  {
    srcUrl: 'https://preview.ibb.co/kPE1D6/clouds.jpg',
    previewUrl: 'https://preview.ibb.co/kPE1D6/clouds.jpg'
  },
  {
    srcUrl: 'https://preview.ibb.co/mwsA6R/img7.jpg',
    previewUrl: 'https://preview.ibb.co/mwsA6R/img7.jpg'
  },
  {
    srcUrl: 'https://preview.ibb.co/kZGsLm/img8.jpg',
    previewUrl: 'https://preview.ibb.co/kZGsLm/img8.jpg'
  }
];
Let's find the array item where srcUrl is equal to "https://preview.ibb.co/kPE1D6/clouds.jpg"

const srcUrl ='https://preview.ibb.co/kPE1D6/clouds.jpg';

// find array element by value
let itemFromArray = this.data.filter(item => item.srcUrl == srcUrl)[0];
This will return us complete item:
{
    srcUrl: 'https://preview.ibb.co/kPE1D6/clouds.jpg',
    previewUrl: 'https://preview.ibb.co/kPE1D6/clouds.jpg'
  },

OK, but how to find index number of that same element inside of array:
const srcUrl ='https://preview.ibb.co/kPE1D6/clouds.jpg';

let index = this.data.findIndex(function(el) {
  return el.srcUrl == srcUrl;
});
This will return us number 1, which is the index number of array item where  srcUrl ='https://preview.ibb.co/kPE1D6/clouds.jpg'

And that was it, plain and simple...
Easy peasy lemon squeezy