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.
Related
This question already has answers here:
Javascript - sort array based on another array
(26 answers)
Closed last year.
I have two arrays a and b like this:
const a = [1,2,3,4]
const b = ['1','2','3','4'] // could be 'a','b','c','d'
const reordered_a = [4,1,3,2] // based on this reordering
function reorder_b() {
// should return ['4','1','3','2']
}
How can I return reordered version of b based on reordered positions in reordered_a?
You could take an object with the indices for the values and map the pattern with the values of the indices.
const a = [1, 2, 3, 4]
const b = ['1', '2', '3', '4'] // could be 'a','b','c','d'
const reordered_a = [4, 1, 3, 2] // based on this reordering
function reorder_b() {
const references = Object.fromEntries(Object.entries(a).map(a => a.reverse()));
return reordered_a.map(k => b[references[k]]);
}
console.log(reorder_b()); // 4 1 3 2
What you got to do is first use every pair of elements el1 and el2 and convert them to numbers. Then once they're converted, make sure that the latter is bigger than the latter by checking their difference :
return b.sort((el1,el2)=>Number(el2)-Number(el1))
This question already has answers here:
Check if an array includes an array in javascript
(3 answers)
Why doesn't equality check work with arrays [duplicate]
(6 answers)
Closed 1 year ago.
Why are the last two console.logs showing false?
const a = 'one';
const b = 'two';
const myArray = [[ 'one', 'two'], ['three', 'four'], ['five', 'six']];
console.log([a, b]);
console.log(myArray[0]);
console.log(myArray.includes([a, b]));
console.log(myArray[0] === [a, b]);
in JavaScript arrays and objects are compared by reference and not by value.
One solution I suggest is to use JSON.stringify()
a = ["a", "b"]
b = ["a", "b"]
console.log(JSON.stringify(a) == JSON.stringify(a)) // return true
Array.prototype.includes() and triple equal operator === work with references, they don't compare the elements of the arrays, they compare the array references themselves:
console.log([] === []); // false
const a = [];
const b = a;
console.log(a === b); // true
You could first convert the array (object) to a string using JSON.stringify(), then compare the string:
const a = 'one';
const b = 'two';
const myArray = [
['one', 'two'],
['three', 'four'],
['five', 'six']
];
console.log(JSON.stringify(myArray[0]) === JSON.stringify([a, b]));
You can also run through the separate values using every() and compare them like this:
const a = 'one';
const b = 'two';
const myArray = [[ 'one', 'two'], ['three', 'four'], ['five', 'six']];
const isequal = [a, b].length === myArray[0].length && [a, b].every((value, i) => value === myArray[0][i]);
console.log(isequal);
Arrays in JavaScript are Objects and Objects comparison will always return false if the referenced objects aren't the same.
If you want to compare arrays you have to write a function for this or use isEqual func from lodash
https://lodash.com/docs/4.17.15#isEqual
This question already has answers here:
Variable name as a string in Javascript
(20 answers)
Closed 4 years ago.
var a = "aa", b= "bb",c ="cc", d="dd", e="ee";
array = [a,b,c,d,e] // outputs ["aa", "bb", "cc", "dd", "ee"];
However is there a possibility in javascript to convert the variables (a, b,c,d,e) into strings?
Like: "a", "b", "c", "d", "e"??
P.S: the array values could be dynamic as well or more than the length mentioned above.
Thanks for the help!!
You could do this with ES6 shorthand property names and return array of strings.
let a = "aa", b= "bb",c ="cc", d="dd", e="ee";
let strings = Object.keys({a, b, c, d, e});
console.log(...strings)
Something like this
var a = "aa", b= "bb",c ="cc", d="dd", e="ee";
var array = [a,b,c,d,e];
({a,b,c,d,e} = array)
var keys = Object.keys({a,b,c,d,e});
console.log(keys)
console.log(array)
This question already has answers here:
JavaScript: How to join / combine two arrays to concatenate into one array?
(3 answers)
Closed 7 years ago.
var ourArray = ["Stimpson", "J", ["cat"]];
ourArray.pop(); // ourArray now equals ["Stimpson", "J"]
ourArray.push(["happy", "joy"]); // ourArray now equals ["Stimpson", "J", ["happy", "joy"]]
var myArray = ["John", 23, ["cat", 2]];
myArray.pop();
// Only change code below this line.
*myArray.push(["dog", 3]);*
// Only change code above this line.
(function(z){return 'myArray = ' + JSON.stringify(z);})(myArray);
Array.push will push anything onto the array, what you are doing is pushing another array into the array, you will need to push "dog" and 3 without the array.
Array.push can take multiple arguments. So just do myArray.push("dog", 3);
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