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.
CodePudding user response:
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));
CodePudding user response:
I would use Array.prototype.some
const array = [{"grub": [23, 24]}, {"earthworm": [34, 35, 36]}, {"larvae": [77, 78, 79]}]
handleInput()
document.querySelector('input').addEventListener('input', ({ target: { value } }) => handleInput(value))
function handleInput(value) {
const isItem = isValueInNestedArray( value, array)
document.querySelector('p').textContent = isItem ? 'yes' : 'no'
}
function isValueInNestedArray(value, array) {
return array.some(item => Object.values(item).some(arr => arr.some(coord => coord === value)))
}
<input>
<p></p>