Answers for "compare arrays javascript"

2

js compare lists

// compare two arrays where order might differ
const array1 = [1,2,3,4,5];
const array2 = [3,4,1,2,5];

const compareArrays = (array1, array2) => {
  return (
    array1.length === array2.length && 
    array1.every((el) => array2.includes(el));
  );
};

compareArrays(array1, array2); // true
Posted by: Guest on August-05-2021
4

javascript compare two arrays of objects get same elements

var result = result1.filter(function (o1) {
    return result2.some(function (o2) {
        return o1.id === o2.id; // return the ones with equal id
   });
});
// if you want to be more clever...
let result = result1.filter(o1 => result2.some(o2 => o1.id === o2.id));
Posted by: Guest on August-03-2020
6

javascript compare arrays

Array.prototype.equals = function(arr2) {
  return (
    this.length === arr2.length &&
    this.every((value, index) => value === arr2[index])
  );
};

[1, 2, 3].equals([1, 2, 3]);	// true
[1, 2, 3].equals([3, 6, 4, 2]);	// false
Posted by: Guest on October-07-2020
4

best way compare arrays javascript

// To compare arrays (or any other object):
// Simple Array Example:
const array1 = ['potato', 'banana', 'soup']
const array2 = ['potato', 'orange', 'soup']

array1 === array2;
// Returns false due to referential equality
JSON.stringify(array1) === JSON.stringify(array2);
// Returns true 


// Another Example:
const deepArray1 = [{test: 'dummy'}, [['woo', 'ya'], 'weird']]
const deepArray2 = [{test: 'dummy'}, [['woo', 'ya'], 'weird']]

deepArray1 === deepArray2;
// Returns false due to referential equality
JSON.stringify(deepArray1) === JSON.stringify(deepArray2);
// Returns true
Posted by: Guest on September-26-2020
1

comparing two arrays in javascript

const arr1 = [1, 2, 3];
const arr2 = [1, 3, 3];

if (arr1.length !== arr2.length) return console.log("false");
for (let i = 0; i < arr1.length; i++) {
    for (let j = 0; j < arr2.length; j++) {
        if (arr1[i] === arr2[j]) {
            console.log("yes match", arr1[i], arr2[j]);
            continue;
        }
        console.log("no match", arr1[i], arr2[j]);
    }
}
Posted by: Guest on March-02-2021
1

how to compare two arrays javascript

function arraysAreIdentical(arr1, arr2){
    if (arr1.length !== arr2.length) return false;
    for (var i = 0, len = arr1.length; i < len; i++){
        if (arr1[i] !== arr2[i]){
            return false;
        }
    }
    return true; 
}
Posted by: Guest on September-07-2020

Code answers related to "compare arrays javascript"

Code answers related to "Javascript"

Browse Popular Code Answers by Language