-1

I'm wondering if there is a short way to compare two arrays like:

[1, 2, 3, 4].equals([1, 2, *, 4]) // where * is any value, I want this expression to be true

Or is there a way to be more specific

[1, 2, 3, 4].equals([1, 2, 0 or 2 or 5, 4]) // true
Mateusz
  • 87
  • 1
  • 8

2 Answers2

1
const compareArraysExceptIndices = (xs, ys, is = [], alts = []) =>
  xs.reduce((prev, curr, index) => {
    const isMatch = ys[index] === curr
    const isValidAlternative = alts.length
      ? is.includes(index) && alts.includes(ys[index])
      : is.includes(index)
    return prev && (isMatch || isValidAlternative)
  }, true)

console.log(compareArraysExceptIndices([1,2,3], [1,2,3])) // true
console.log(compareArraysExceptIndices([1,2,3], [1,1,3])) // false
console.log(compareArraysExceptIndices([1,2,3], [1,1,3], [1])) // true
console.log(compareArraysExceptIndices([1,2,3], [1,1,3], [1], [1])) // true
console.log(compareArraysExceptIndices([1,2,3], [1,1,3], [1], [2])) // true

This will handle all the cases you're asking about.

Zac Anger
  • 6,983
  • 2
  • 15
  • 42
0

I suppose you intend the * as a wildcard:

const arrCmp = (arr1, arr2) => {
  const len = arr1.length;

  for (let i = 0; i < len; i++) {
    if (arr1[i] !== arr2[i] && arr1[i] !== "*" && arr2[i] !== "*") return false;
  }

  return true;
};
domenikk
  • 1,723
  • 1
  • 10
  • 12