skip to Main Content

I have an array of objects:

const arr = [
{ puzzle: [1,3,4,8,0,2,7,6,5], children: [] }, 
{ puzzle: [1,2,3,4,5,6,7,8] }
]

And I have an object:

const element = { puzzle: [1,3,4,8,0,2,7,6,5], children: ["1"]}

Im trying to see if element.puzzle is a value for a property of any of the objects in the array – in this particular example
element.puzzle === arr[0].puzzle, but a few methods I tried give the wrong result, so obviously I`m wrong…

array.some() method gives wrong result

arr.some(item => item.puzzle === element.puzzle) // gives false
arr.find(item=>item.puzzle === element.puzzle) //gives undefined

2

Answers


  1. For each item in the array, check to see if at least one has a puzzle that has the same length and matches every index/value in the element’s puzzle.

    const
      arr = [
        { puzzle: [1,3,4,8,0,2,7,6,5], children: [] }, 
        { puzzle: [1,2,3,4,5,6,7,8] }
      ],
      element = { puzzle: [1,3,4,8,0,2,7,6,5], children: ["1"]}
    
    const arrHasPuzzle = arr.some(({ puzzle }) =>
      puzzle.length === element.puzzle.length &&
      puzzle.every((e, i) => e === element.puzzle[i]));
    
    console.log(arrHasPuzzle); // true
    Login or Signup to reply.
  2. The problem is that the both of the puzzles are different instances of arrays. And since arrays are objects they’re treated as different values when comparing equality, even if they contain the same values.

    [1,2,3] === [1,2,3] //false
    

    Instead, you’re going to have to compare the values of every element in both arrays with each other to tell if they’re "equivalent".

    arr.some(item => item.puzzle.every((e, i) => element.puzzle[i] === e))
    arr.find(item => item.puzzle.every((e, i) => element.puzzle[i] === e))
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search