Search code examples
javascriptarraysobjectiteration

How can I get values of array out of object in array?


I'm building a version of battleship where the ships are worms and the player is the bird...if that explains the naming of things.

I'm having a moment. I need to iterate through the values of a nested array of coordinates but I simply cannot figure it out.

Here is what array looks like:

[{"grub": [23, 24]}, {"earthworm": [34, 35, 36]}, {"larvae": [77, 78, 79]}]

I need to iterate through all the nested objects, and then iterate through the array inside that nested object to see if the input matches values.

Function input will be a coordinate with 2 digits (example '84')

Output should be a boolean stating if the coordinate exists in any of the arrays that are a value of the object.

I have lots of ideas, but none have been successful.


Solution

  • const data = [{"grub": [23, 24]}, {"earthworm": [34, 35, 36]}, {"larvae": [77, 78, 79]}];
    
    const f=(n,data)=>data.map(Object.values).some(([i])=>i.includes(n));
    
    console.log(f(35, data));
    console.log(f(84, data));