3
How to Compare an Array of Numbers in JavaScript
source link: https://masteringjs.io/tutorials/fundamentals/compare-array-of-numbers
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
How to Compare an Array of Numbers in JavaScript
Nov 16, 2021
To check if two arrays of numbers are identical, you can use the every()
function as shown below.
const array1 = [1, 1, 1, 1, 1];
const array2 = [1, 1, 1, 1, 1];
const array3 = [1, 2, 3, 4, 5, 6];
function numberArrayEquals(array1, array2) {
return array1.length === array2.length &&
array1.every((v, i) => array2[i] == array1[i]);
}
numberArrayEquals(array1, array2); // true
numberArrayEquals(array1, array3); // false
Alternative Using JSON.stringify()
You can also use JSON.stringify()
to check if the two arrays are identical.
const array1 = [1, 1, 1, 1, 1];
const array2 = [1, 1, 1, 1, 1];
const array3 = [1, 2, 3, 4, 5, 6];
// JSON.stringify(array1) => "[1,1,1,1,1]"
JSON.stringify(array1) === JSON.stringify(array2); // true
JSON.stringify(array1) === JSON.stringify(array3); // false
More Fundamentals Tutorials
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK