-1

I have an array in which should look like this:

const arr = [
 {index:12, data: a},
 {index:15, data: w},
 {index:32, data: e},
 {index:42, data: g}
]

Is it possible to find out if an index exists using the arr.includes() method? if yes, how then. if no, what is the best options to find if an index exists?

fatihyildizhan
  • 8,614
  • 7
  • 64
  • 88
DGE
  • 11
  • what do you want as result? have you tried anything? what does not work? – Nina Scholz Apr 27 '20 at 16:54
  • Does this answer your question? [Get the index of the object inside an array, matching a condition](https://stackoverflow.com/questions/15997879/get-the-index-of-the-object-inside-an-array-matching-a-condition) – Kiran Shinde Apr 27 '20 at 16:55

3 Answers3

1

You can use array.some() and pass an arrow function:

    const arr = [
       {index:12, data: 'a'},
       {index:15, data: 'w'},
       {index:32, data: 'e'},
       {index:42, data: 'g'}
    ]
    
    let exists = arr.some(x => x.index === 12);
    console.log(exists);
mickl
  • 48,568
  • 9
  • 60
  • 89
1

You can use filter() and you will also recieve array of items with that index:

  const arr = [
       {index:12, data: 'x'},
       {index:15, data: 'x'},
       {index:32, data: 'x'},
       {index:42, data: 'x'}
  ];
  
  const targetIndex = 42;
  const filtered = arr.filter(item=>item.index===targetIndex);
  console.log(`There ${filtered.length?'is':'is not'} index ${targetIndex} in array`);

Or you can use some()

const arr = [
     {index:12, data: 'x'},
     {index:15, data: 'x'},
     {index:32, data: 'x'},
     {index:42, data: 'x'}
];
      
const targetIndex = 42;
const isThere = arr.some(item=>item.index===targetIndex);
 console.log(`There ${isThere?'is':'is not'} index ${targetIndex} in array`);
Jax-p
  • 7,225
  • 4
  • 28
  • 58
0

Using includes (or filter, some) can be expensive. If you have a large array (hundreds or more), or you need to determine inclusion often, then it can be very slow. That's because these functions loop through the array looking inside of the objects with the function you provide until the outcome is reached.

If performance is a concern you may find that building an indexing object is best for you. For example:

const byIndices = {};
arr.forEach(obj => byIndices[obj.index] = obj);
if (byIndices[12]) console.log("item 12 is",byIndices[12].data)

With this approach you loop through the entire array once (the forEach loop) to build the indexing object byIndices, then you can use direct object syntax to not only determine existence, but also get at the object.

Since Javascript is optimized for working with objects, doing lookups like byIndices[val] are very quick, and since it's all object references it's not too bad for memory use either.

However for small arrays, or if you only need to find entries occasionally then it's probably simplest to use some or filter to do the job.

Always Learning
  • 5,510
  • 2
  • 17
  • 34