This question already has answers here:
How to check if two arrays are equal with JavaScript? [duplicate]
(16 answers)
Closed 10 years ago.
I want to check if the two arrays are identical
(not content wise, but in exact order).
For example:
array1 = [1,2,3,4,5]
array2 = [1,2,3,4,5]
array3 = [3,5,1,2,4]
Array 1 and 2 are identical but 3 is not.
Is there a good way to do this in JavaScript?
So, what's wrong with checking each element iteratively?
function arraysEqual(arr1, arr2) {
if(arr1.length !== arr2.length)
return false;
for(var i = arr1.length; i--;) {
if(arr1[i] !== arr2[i])
return false;
}
return true;
}
You could compare String representations so:
array1.toString() == array2.toString()
array1.toString() !== array3.toString()
but that would also make
array4 = ['1',2,3,4,5]
equal to array1 if that matters to you
Related
This question already has answers here:
Determine whether an array contains a value [duplicate]
(18 answers)
Closed 1 year ago.
I'm trying to check for an if condition iteratively inside a for loop. That means some expressions of if conditions need to be generated iteratively as shown in the below example
let union = [1,2,3,4,5,6,7,8,9]
let control = [2,4,6]
let result = []
for(let i=0; i<union.length; i++){
if(union[i] % 2 == 0 && union[i] !== control[i]){
result.push(union[i])
}
}
In the above example union[i] !== control[i] is the conditional expression that need to be validated/generated iteratively. In words we can state the problem as
result array should contain only even numbers from the union array and it should not contain any element from the control array
So the result array should be [8]
result array should contain only even numbers from the union array and it should not contain any element from the control array
let union = [1,2,3,4,5,6,7,8,9]
let control = [2,4,6]
let result = []
union.forEach(item => {
if(item % 2 == 0 && !control.includes(item)) {
result.push(item);
}
});
The .includes method checks if the item is in the array.
or just a simple filter
const result = union.filter(item => item % 2 == 0 && !control.includes(item));
1 more option.
remove duplicate item between 2 arrays then just check for even numbers.
let union = [1,2,3,4,5,6,7,8,9]
let control = [2,4,6]
let result = []
union = union.filter(function(val) {
return control.indexOf(val) == -1;
});
for(let i=0; i<union.length; i++){
if(union[i] % 2 == 0){
result.push(union[i])
}
}
You can modify the check and see if control.includes(union[i]). This will be true when control includes the current union variable. This is also true for the other way round, meaning if control includes the union variable, the union variable also contains the control variable. Negate the check with ! to see if it doesn't include this value.
let union = [1,2,3,4,5,6,7,8,9]
let control = [2,4,6]
let result = []
for(let i=0; i<union.length; i++){
if(union[i] % 2 == 0 && !control.includes(union[i])){
result.push(union[i])
}
}
console.log(result);
Use Array#filter with a Set.
The problem with your code is for every item in union you need to check every item in control, whether it exists or not, which you are not doing.
And I would recommend using a Set instead of searching in an array repeatedly.
const
union = [1, 2, 3, 4, 5, 6, 7, 8, 9],
control = [2, 4, 6],
result = ((s) => union.filter((u) => !(u&1) && !s.has(u)))(new Set(control));
console.log(result);
This question already has answers here:
How to compare arrays in JavaScript?
(55 answers)
Closed 4 years ago.
Is there any function in JS to check "If an array exists in a larger array?"
I tried array.includes() and array.indexOf() but they didn't work for me...
for example I except a true return value here:
parent = [[a,b],[c,d],[e,f]]
child = [c,d]
Your includes fails because you're trying to match reference. A well detailed explanation you can see on this answer https://stackoverflow.com/a/54363784/9624435
You can use filter and every
let parent = [['a','b'],['c','d'],['e','f']];
let child = ['c','d'];
let result = parent.filter(arr => arr.every(v => child.includes(v)));
console.log(result);
Let's focus on why .includes fail.
Array.includes uses following function to check equality:
function sameValueZero(x, y) {
return x === y || (typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y));
}
Since you have arrays as element, they are copied using references, so you are checking references of arrays instead. Hence it fails.
Following is a sample:
const item1 = ['a', 'b'];
const item2 = ['c', 'd'];
const item3 = ['e', 'f']
const parent = [item1, item2, item3]
const child = item3;
console.log(parent.includes(child))
Hence, you will have to go deeper and check individual values.
References:
Why [] == [] is false in JavaScript?
Array.includes polyfill
How to compare arrays in JavaScript?: as rightly suggested by #Chris G
This question already has answers here:
How to compare arrays in JavaScript?
(55 answers)
Closed 5 years ago.
I have an array of two nested arrays.
var array = [ [a,b,c], [a,b,c] ]
Despite the array elements being identical, the following code returns true:
if (array[0] !== array[1]) {
console.log(array[0])
console.log(array[1])
}
// [a,b,c]
// [a,b,c]
And the following code returns false:
if (array[0] === array[1]) {
console.log(array[0])
console.log(array[1])
}
It seems to be comparing the indices instead of the elements.
What is going on here?
Sometimes I will be comparing 3 or possibly even 4 nested arrays to each other. For instance, if ( array[0] === array[1] || array[0] === array[2] || array[1] === array[2] ) // do this. Notably, a and c will always be references to actual HTML elements, whereas b will be a number. Is there not a simple way to accomplish this nowadays?
You are comparing object references, not object values. The pointers to memory are different, and as a result the comparison is false.
Here is a simple example using html elements in the arrays.
var a1 = document.querySelectorAll('div');
var a2 = document.querySelectorAll('div');
var a3 = document.querySelectorAll('div');
var array = [Array.from(a1),Array.from(a2),Array.from(a3)];
console.log(array[0].every((v,i) => array.slice(1).every(ai => v == ai[i])));
<div>1</div><div>2</div><div>3</div>
This question already has answers here:
How to compare two arrays in node js?
(8 answers)
Closed 8 years ago.
Say I have two arrays
["a", "b", "c"]
["c", "a", "b"]
What is the best way to compare these two arrays and see if they are equal (they should come as equal for the above scenario)
function compareArrays(array1, array2) {
array1 = array1.slice();
array2 = array2.slice();
if (array1.length === array2.length) { // Check if the lengths are same
array1.sort();
array2.sort(); // Sort both the arrays
return array1.every(function(item, index) {
return item === array2[index]; // Check elements at every index
}); // are the same
}
return false;
}
console.assert(compareArrays(["a", "b", "c"], ["c", "a", "b"]) === true);
You can try with _.difference
var diff = _(array1).difference(array2);
if(diff.length > 0) {
// There is a difference
}
this will not work because different returns diff from first array.
_.difference(['a'] ,['a','b']) is 0 but two array is not equal.
This question already has answers here:
Natural sort of alphanumerical strings in JavaScript
(6 answers)
Closed 8 years ago.
I am very new to TypeScript and Javascript. I am trying to sort an array that contains both numbers and strings e.g. (1, 5, 27.5, Other, Mobile). I want it to display the numbers ascending first and then text after in alphabetically order. I tried
myarr.sort (function (a, b) {
return (a-b);
}
I get an error saying the operator '-' cannot be applied to types string and string
If you don't need to handle browsers lower than IE9, filter is a good choice.
Get the numbers and sort them:
var nums = arr.filter(function (el) {
return typeof el === 'number';
}).sort();
Get the strings and sort them:
var strings = arr.filter(function (el) {
return typeof el === 'string';
}).sort();
Concatonate the two arrays:
var result = nums.concat(strings);
Demo.