-2

How I can scan my array within array if there is equal array element. I want to check if its true or false

// the array to be scan 
const array = [
[0, 1, 2],
[3, 4, 5], 
[6, 7, 8],
]

// the new array
const newArray = [0, 1, 2]

Krune
  • 3
  • 3
  • Have you checked [how-to-compare-arrays-in-javascript](https://stackoverflow.com/questions/7837456/how-to-compare-arrays-in-javascript)? – flyingfox Nov 25 '22 at 06:35
  • not yet, but my problem is, the array is inside of array so what will I need to do to it in order to compare it – Krune Nov 25 '22 at 06:40

4 Answers4

0

You can use every method to check all the items.

array.filter((arr)=>arr.every((item,index)=>newArray[index]===item))
Hao-Jung Hsieh
  • 516
  • 4
  • 9
  • Doesn't work when the `newArray` has same elements at the index but has more elements: `array = [[1]], newArray = [1,2,3]` – adiga Nov 25 '22 at 06:50
0

Based on anwser from how-to-compare-arrays-in-javascript,you just need to iterate the first array and then compare them

const array = [
[0, 1, 2],
[3, 4, 5], 
[6, 7, 8],
]

// the new array
const newArray1 = [0, 1, 2]
const newArray2 = [0, 1, 3]

const checkArray = (array1,array2) => {
  for(let arr of array1){
   if(arr.length === array2.length && arr.every((v,i) => v === array2[i])){
     return true
   } 
  }
  return false
}

console.log(checkArray(array,newArray1))
console.log(checkArray(array,newArray2))
flyingfox
  • 13,414
  • 3
  • 24
  • 39
0

run a foreach or for loop with a combination of name.find(x => x.ref === value);
or use array.filter((arr)=>arr.every((item,index)=>newArray[index]===item))

Harvir
  • 131
  • 7
  • Doesn't work when the `newArray` has same elements at the index but has more elements: `array = [[1]], newArray = [1,2,3]` – adiga Nov 25 '22 at 06:50
0

const array = [
  [0, 1, 2],
  [3, 4, 5],
  [6, 7, 8],
];

const newArray = [0, 1, 2]

let isPresent = false;

for (let i = 0; i < array.length; i++) {
  if (JSON.stringify(array[i]) == JSON.stringify(newArray)) {
    isPresent = true
    break
  }
}
console.log(isPresent)

After stringifying the array you are able to compare directly in js and If it matches I changed the boolean value to true.

In case you have any doubts feel free to comment.

adiga
  • 34,372
  • 9
  • 61
  • 83
Mayank Gupta
  • 153
  • 5