compare if two arrays are equal javascript code example

Example 1: check if 2 arrays are equal javascript

const a = [1, 2, 3];
const b = [4, 5, 6];
const c = [1, 2, 3];

function arrayEquals(a, b) {
  return Array.isArray(a) &&
    Array.isArray(b) &&
    a.length === b.length &&
    a.every((val, index) => val === b[index]);
}

arrayEquals(a, b); // false
arrayEquals(a, c); // true

Example 2: diff two arrays javascript

function diffArray(arr1, arr2) {
  return arr1
    .concat(arr2)
    .filter(item => !arr1.includes(item) || !arr2.includes(item));
}

Example 3: javascript compare arrays

Array.prototype.equals = function(arr2) {
  return (
    this.length === arr2.length &&
    this.every((value, index) => value === arr2[index])
  );
};

[1, 2, 3].equals([1, 2, 3]);	// true
[1, 2, 3].equals([3, 6, 4, 2]);	// false

Example 4: check if 2 arrays are equal javascript

var arraysMatch = function (arr1, arr2) {

	// Check if the arrays are the same length
	if (arr1.length !== arr2.length) return false;

	// Check if all items exist and are in the same order
	for (var i = 0; i < arr1.length; i++) {
		if (arr1[i] !== arr2[i]) return false;
	}

	// Otherwise, return true
	return true;

};

Tags:

Php Example