Search code examples
javascriptarraysobjectsearch

How to return index of object element matched from a check array


i hope the title is properly expressive of the problem i'm trying to solve. what i need to do is search an object for a matching element from a check array and return the object's index of that match. to whit:

const checkArray = ['18A38', '182B92', '85F33'];    //  these are the values to match
const dataOject = [
  0 => ['id'=>'853K83', 'isGO'=>false],             //  this is the object to search through
  1 => ['id'=>'85F33', 'isGO'=>true],
  2 => ['id'=>'97T223', 'isGO'=>true],
  3 => ['id'=>'18A38', 'isGO'=>false],
  4 => ['id'=>'182B92', 'isGO'=>true],
  ...
];

what i need to do is find the matching index so i can then check if the isGO flag is set. this is what i was trying when i dead-ended:

results = checkArray.forEach(function(value, index){
  if (dataObject.findIndex(function(k=> k == value))) results.push(k);
    //  i know 'results.push(k)' is not right, but it's the essence of what i want.  :P
};

what i am expecting is that results will be an array of indexes that i can then go back and check the dataObject for set isGO flags; results should look like this:

results = [3, 1, 4];

but i'm stumped on how to make the findIndex complete properly. i've read this and this and this but, while educational, they aren't dealing with an array and an object. i do have underscore in this project, but, again, haven't found anything that i comprehend as useful in this scenario.

how do i get this to run in a way that gives me what i need?


Solution

  • Instead of returning the indexes, isn't it easier to return the objects themselves?

    const matchedObjects = dataObject.filter(
       ({ id }) => checkArray.includes(id)
    );
    

    That will return all objects having id found in your checkArray.

    Having these objects in matchedObjects, you can iterate through them and do whatever you wish.