Compare two arrays
Check the same length and the same items in the same order.
function isEqual({ a, b }) { return a.length === b.length && a.every((value, i) => Object.is(value, b[i])); }
Input & expected output
Input
{
"a": [
1,
2,
3
],
"b": [
1,
2,
3
]
}Expected output
trueThe edge case
Input
{
"a": [
1,
2,
3
],
"b": [
1,
2,
"3"
]
}Expected output
falseKnow the limits
- Shallow comparison with Object.is. The original JSON.stringify variant treats undefined and null alike and depends on key order for nested objects.
The function above is the implementation used by the lab. The lab validates JSON types and caps size before execution; include equivalent validation when accepting untrusted input in your application.
Source & maintenance
Based on Compare two arrays from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.
Keeps the element-wise variant with Object.is. Original MDX retained as inert source evidence.
Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.
Keep exploring
- Clone an array — Create a new array without copying the objects inside it.
- Remove duplicate values — Keep the first occurrence of each value, in its original order.
- Flatten a nested array — Turn a nested array into one sequence of values.