EN
JavaScript - use lodash to compare array items existence without order
0 points
In this article, we would like to show you how to use lodash to compare if arrays are the same but with changed items order in JavaScript.
In this example, we use _.isEqual()
method with sort()
to check if array items are the same (or the same with changed order).
xxxxxxxxxx
1
2
<html>
3
<head>
4
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
5
</head>
6
<body>
7
<script>
8
9
var array1 = [['a', 'b'], ['b', 'c']];
10
var array2 = [['b', 'c'], ['a', 'b']];
11
12
var result = _.isEqual(array1.sort(), array2.sort());
13
14
console.log(result); // true
15
16
</script>
17
</body>
18
</html>
In this example, we use _.isEqual()
method with _.sortBy()
to compare arrays.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
5
</head>
6
<body>
7
<script>
8
9
var array1 = [['a', 'b'], ['b', 'c']];
10
var array2 = [['b', 'c'], ['a', 'b']];
11
12
var result = _.isEqual(_.sortBy(array1), _.sortBy(array2));
13
14
console.log(result); // true
15
16
</script>
17
</body>
18
</html>