1

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.

isherwood
61.4k16 gold badges122 silver badges173 bronze badges
asked Nov 16, 2022 at 21:15
3
  • 4
    Please show the ideas you've attempted and how they came up short. Commented Nov 16, 2022 at 21:17
  • 3
    that data structure looks weird, why can't you use one single object? Commented Nov 16, 2022 at 21:18
  • 3
    In general, an array of objects with different keys in each object is a poor idea. Either use a single object, or an array of objects with consistent keys, e.g. {name: "grub", coordinates: [23, 24]} Commented Nov 16, 2022 at 21:19

2 Answers 2

1

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));

answered Nov 16, 2022 at 21:20
Sign up to request clarification or add additional context in comments.

1 Comment

Simple, I don't understand why it works yet but I'm going to read documentation so I never have to ask this question again :)
1

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>

answered Nov 16, 2022 at 21:22

1 Comment

Thank you much, I love how you provided detail on how to implement the solution. Very much appreciated.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.