0

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?

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
WhiteRau
  • 818
  • 14
  • 32
  • Assuming we fix the syntax of `dataObject` so it's a proper array storing proper objects: `const results = checkArray.map(val => dataObject.findIndex(o => o.id == val));` –  May 09 '20 at 00:01
  • I just copy/paste from `var_dump` and tweak, bud. Sufficient to communicate the idea. At any rate, I'll give your suggestion a whirl. – WhiteRau May 09 '20 at 00:23

2 Answers2

3

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.

Robo Robok
  • 21,132
  • 17
  • 68
  • 126
1

something like that ?

const checkArray = ['18A38', '182B92', '85F33'] 

const dataOject =
  [ { id:'853K83', isGo:false }
  , { id:'85F33',  isGo:true  }
  , { id:'97T223', isGo:true  }
  , { id:'18A38',  isGo:false }
  , { id:'182B92', isGo:true  }
  ];

const result = checkArray.map(val=>dataOject.findIndex(el=>el.id===val) )


console.log( JSON.stringify(result))
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40