如何比较两个数组在使用Javascript时是相等的?

时间:2021-07-06 12:08:22

I want position of the array is to be also same and value also same.

我想要数组的位置也是一样的值也是一样的。

var array1 = [4,8,9,10];
var array2 = [4,8,9,10];

I tried like this

我试着这样

var array3 = array1 === array2   // returns false

10 个解决方案

#1


111  

You could use Array.prototype.every().(A polyfill is needed for IE < 9 and other old browsers.)

您可以使用Array.prototype.every()。(IE < 9和其他旧浏览器需要一个polyfill。)

var array1 = [4,8,9,10];
var array2 = [4,8,9,10];

var is_same = (array1.length == array2.length) && array1.every(function(element, index) {
    return element === array2[index]; 
});

THE WORKING DEMO.

工作演示。

#2


31  

A less robust approach, but it works.

一种不那么稳健的方法,但它确实有效。

a = [2, 4, 5].toString();
b = [2, 4, 5].toString();

console.log(a===b);

#3


10  

var array3 = array1 === array2

That will compare whether array1 and array2 are the same array object in memory, which is not what you want.

这将比较array1和array2是否在内存中是相同的数组对象,这不是您想要的。

In order to do what you want, you'll need to check whether the two arrays have the same length, and that each member in each index is identical.

为了实现您想要的效果,您需要检查两个数组的长度是否相同,以及每个索引中的每个成员是否相同。

Assuming your array is filled with primitives—numbers and or strings—something like this should do

假设数组中充满了原语(数字或字符串),那么就应该这样做

function arraysAreIdentical(arr1, arr2){
    if (arr1.length !== arr2.length) return false;
    for (var i = 0, len = arr1.length; i < len; i++){
        if (arr1[i] !== arr2[i]){
            return false;
        }
    }
    return true; 
}

#4


4  

You could try this simple approach

你可以试试这个简单的方法。

var array1 = [4,8,9,10];
var array2 = [4,8,9,10];

console.log(array1.join('|'));
console.log(array2.join('|'));

if (array1.join('|') === array2.join('|')) {
	console.log('The arrays are equal.');
} else {
	console.log('The arrays are NOT equal.');
}

array1 = [[1,2],[3,4],[5,6],[7,8]];
array2 = [[1,2],[3,4],[5,6],[7,8]];

console.log(array1.join('|'));
console.log(array2.join('|'));

if (array1.join('|') === array2.join('|')) {
	console.log('The arrays are equal.');
} else {
	console.log('The arrays are NOT equal.');
}

If the position of the values are not important you could sort the arrays first.

如果值的位置不重要,可以先对数组进行排序。

if (array1.sort().join('|') === array2.sort().join('|')) {
    console.log('The arrays are equal.');
} else {
    console.log('The arrays are NOT equal.');
}

#5


3  

A more modern version:

一个更现代版:

function arraysEqual(a, b) {
  a = Array.isArray(a) ? a : [];
  b = Array.isArray(b) ? b : [];
  return a.length === b.length && a.every((el, ix) => el === b[ix]);
}

Coercing non-array arguments to empty arrays stops a.every() from exploding.

将非数组参数强制转换为空数组将阻止a.a every()爆炸。

If you just want to see if the arrays have the same set of elements then you can use Array.includes():

如果您只是想看看数组是否具有相同的元素集,那么您可以使用array. include ():

function arraysContainSame(a, b) {
  a = Array.isArray(a) ? a : [];
  b = Array.isArray(b) ? b : [];
  return a.length === b.length && a.every(el => b.includes(el));
}

#6


3  

Use lodash. In ES6 syntax:

使用lodash。在ES6语法:

import isEqual from 'lodash/isEqual';
let equal = isEqual([1,2], [1,2]);  // true

Or previous js versions:

或之前的js版本:

var isEqual = require('lodash/isEqual');
var equal = isEqual([1,2], [1,2]);  // true

#7


1  

If you comparing 2 arrays but values not in same index, then try this

如果您比较两个数组,但值不相同的索引,那么尝试这个

var array1=[1,2,3,4]
var array2=[1,4,3,2]
var is_equal = array1.length==array2.length && array1.every(function(v,i) { return ($.inArray(v,array2) != -1)})
console.log(is_equal)

#8


0  

Here goes the code. Which is able to compare arrays by any position.

这里的代码。它可以通过任何位置来比较数组。

var array1 = [4,8,10,9];

var array2 = [10,8,9,4];

var is_same = array1.length == array2.length && array1.every(function(element, index) {
    //return element === array2[index];
  if(array2.indexOf(element)>-1){
    return element = array2[array2.indexOf(element)];
  }
});
console.log(is_same);

#9


0  

function isEqual(a) {
if (arrayData.length > 0) {
    for (var i in arrayData) {
        if (JSON.stringify(arrayData[i]) === JSON.stringify(a)) {
            alert("Ya existe un registro con esta informacion");
            return false;
        }
    }
}
}

Check this example

检查这个例子

#10


-1  

Try doing like this: array1.compare(array2)=true

试着这样做:array1.compare(array2)=true

Array.prototype.compare = function (array) {
    // if the other array is a falsy value, return
    if (!array)
        return false;

    // compare lengths - can save a lot of time
    if (this.length != array.length)
        return false;

    for (var i = 0, l=this.length; i < l; i++) {
        // Check if we have nested arrays
        if (this[i] instanceof Array && array[i] instanceof Array) {
            // recurse into the nested arrays
            if (!this[i].compare(array[i]))
                return false;
        }
        else if (this[i] != array[i]) {
            // Warning - two different object instances will never be equal: {x:20} != {x:20}
            return false;
        }
    }
    return true;
}

#1


111  

You could use Array.prototype.every().(A polyfill is needed for IE < 9 and other old browsers.)

您可以使用Array.prototype.every()。(IE < 9和其他旧浏览器需要一个polyfill。)

var array1 = [4,8,9,10];
var array2 = [4,8,9,10];

var is_same = (array1.length == array2.length) && array1.every(function(element, index) {
    return element === array2[index]; 
});

THE WORKING DEMO.

工作演示。

#2


31  

A less robust approach, but it works.

一种不那么稳健的方法,但它确实有效。

a = [2, 4, 5].toString();
b = [2, 4, 5].toString();

console.log(a===b);

#3


10  

var array3 = array1 === array2

That will compare whether array1 and array2 are the same array object in memory, which is not what you want.

这将比较array1和array2是否在内存中是相同的数组对象,这不是您想要的。

In order to do what you want, you'll need to check whether the two arrays have the same length, and that each member in each index is identical.

为了实现您想要的效果,您需要检查两个数组的长度是否相同,以及每个索引中的每个成员是否相同。

Assuming your array is filled with primitives—numbers and or strings—something like this should do

假设数组中充满了原语(数字或字符串),那么就应该这样做

function arraysAreIdentical(arr1, arr2){
    if (arr1.length !== arr2.length) return false;
    for (var i = 0, len = arr1.length; i < len; i++){
        if (arr1[i] !== arr2[i]){
            return false;
        }
    }
    return true; 
}

#4


4  

You could try this simple approach

你可以试试这个简单的方法。

var array1 = [4,8,9,10];
var array2 = [4,8,9,10];

console.log(array1.join('|'));
console.log(array2.join('|'));

if (array1.join('|') === array2.join('|')) {
	console.log('The arrays are equal.');
} else {
	console.log('The arrays are NOT equal.');
}

array1 = [[1,2],[3,4],[5,6],[7,8]];
array2 = [[1,2],[3,4],[5,6],[7,8]];

console.log(array1.join('|'));
console.log(array2.join('|'));

if (array1.join('|') === array2.join('|')) {
	console.log('The arrays are equal.');
} else {
	console.log('The arrays are NOT equal.');
}

If the position of the values are not important you could sort the arrays first.

如果值的位置不重要,可以先对数组进行排序。

if (array1.sort().join('|') === array2.sort().join('|')) {
    console.log('The arrays are equal.');
} else {
    console.log('The arrays are NOT equal.');
}

#5


3  

A more modern version:

一个更现代版:

function arraysEqual(a, b) {
  a = Array.isArray(a) ? a : [];
  b = Array.isArray(b) ? b : [];
  return a.length === b.length && a.every((el, ix) => el === b[ix]);
}

Coercing non-array arguments to empty arrays stops a.every() from exploding.

将非数组参数强制转换为空数组将阻止a.a every()爆炸。

If you just want to see if the arrays have the same set of elements then you can use Array.includes():

如果您只是想看看数组是否具有相同的元素集,那么您可以使用array. include ():

function arraysContainSame(a, b) {
  a = Array.isArray(a) ? a : [];
  b = Array.isArray(b) ? b : [];
  return a.length === b.length && a.every(el => b.includes(el));
}

#6


3  

Use lodash. In ES6 syntax:

使用lodash。在ES6语法:

import isEqual from 'lodash/isEqual';
let equal = isEqual([1,2], [1,2]);  // true

Or previous js versions:

或之前的js版本:

var isEqual = require('lodash/isEqual');
var equal = isEqual([1,2], [1,2]);  // true

#7


1  

If you comparing 2 arrays but values not in same index, then try this

如果您比较两个数组,但值不相同的索引,那么尝试这个

var array1=[1,2,3,4]
var array2=[1,4,3,2]
var is_equal = array1.length==array2.length && array1.every(function(v,i) { return ($.inArray(v,array2) != -1)})
console.log(is_equal)

#8


0  

Here goes the code. Which is able to compare arrays by any position.

这里的代码。它可以通过任何位置来比较数组。

var array1 = [4,8,10,9];

var array2 = [10,8,9,4];

var is_same = array1.length == array2.length && array1.every(function(element, index) {
    //return element === array2[index];
  if(array2.indexOf(element)>-1){
    return element = array2[array2.indexOf(element)];
  }
});
console.log(is_same);

#9


0  

function isEqual(a) {
if (arrayData.length > 0) {
    for (var i in arrayData) {
        if (JSON.stringify(arrayData[i]) === JSON.stringify(a)) {
            alert("Ya existe un registro con esta informacion");
            return false;
        }
    }
}
}

Check this example

检查这个例子

#10


-1  

Try doing like this: array1.compare(array2)=true

试着这样做:array1.compare(array2)=true

Array.prototype.compare = function (array) {
    // if the other array is a falsy value, return
    if (!array)
        return false;

    // compare lengths - can save a lot of time
    if (this.length != array.length)
        return false;

    for (var i = 0, l=this.length; i < l; i++) {
        // Check if we have nested arrays
        if (this[i] instanceof Array && array[i] instanceof Array) {
            // recurse into the nested arrays
            if (!this[i].compare(array[i]))
                return false;
        }
        else if (this[i] != array[i]) {
            // Warning - two different object instances will never be equal: {x:20} != {x:20}
            return false;
        }
    }
    return true;
}