-2

to different two arrays with true or false output. a compare two arrays with function this my code :

    var cekDiff = function (arr1, arr2) {
    var maxLength = 0,
        cekTrue = 0;
    if (arr1.length > arr2.length) maxLength = arr1.length;
    else maxLength = arr2.length;
    for (var i = 0; i < maxLength; i++) {
        if (arr1[i] == arr2[i]) {
            cekTrue++;
        }
    }
    if (cekTrue >= maxLength) return true;
    else return false;
}


if (cekDiff([0, 1, 2, 4, 3], [0, 1, 2, 3, 4])) {
    console.log("match");
} else {
    console.log("different");
}

3 Answers3

0

You're very close, since both the arrays have different order of values and you're matching by index ( newArr1[i] == newArr2[i] ) so you need to sort arrays first then check for equality

var cekDiff = function(arr1, arr2) {
  let newArr1 = [...arr1].sort((a, b) => a - b)
  let newArr2 = [...arr2].sort((a, b) => a - b)
  var maxLength = 0,
    cekTrue = 0;
  if (newArr1.length > newArr2.length) maxLength = arr1.length;
  else maxLength = newArr2.length;
  for (var i = 0; i < maxLength; i++) {
    if (newArr1[i] == newArr2[i]) {
      cekTrue++;
    }
  }
  if (cekTrue >= maxLength) return true;
  else return false;
}


if (cekDiff([0, 1, 2, 4, 3], [0, 1, 2, 3, 4])) {
  console.log("match");
} else {
  console.log("different");
}
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
0

Use reduce to check you arrays

const isArrayExact = (arr1, arr2) => arr1.reduce((acc, curr, index) => acc && ,true)

Compare each element, but check if exist

0

You could count each element with either incrementing the counter or decrementing. then get the value and if all zeros, return true.

function sameValues(a, b) {
    const
        counter = (o, i) => k => o[k] = (o[k] || 0) + i,
        count = {};
    
    a.forEach(counter(count, 1));
    b.forEach(counter(count, -1));
    
    return !Object.values(count).some(Boolean);
}


console.log(sameValues([0, 1, 2, 4, 3], [0, 1, 2, 3, 4]));
console.log(sameValues([0, 1, 2, 4, 3], [0, 1, 2, 3, 4, 5]));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392