E
E
efimenko_b2015-07-13 18:12:25
Python
efimenko_b, 2015-07-13 18:12:25

How to compare two arrays in js?

There are 2 arrays.
Identical in content, only one has one more element.
How to compare them in order to pull out the element which is missing in the second array?
Thanks in advance.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Stalker_RED, 2015-07-13
@efimenko_b

Updated the answer, the old implementation was with a bug.

function diff(a1, a2) {
    return a1.filter(i=>a2.indexOf(i)<0)
    .concat(a2.filter(i=>a1.indexOf(i)<0))
}
function compare(a1, a2) {
    return a1.length == a2.length && a1.every((v,i)=>v === a2[i])
}

jsfiddle.net/Stalk/7h5ahq5k/2
upd: ES7 (2016) introduced the includes method
const diff = function(a1, a2) {
    return a1.filter(i=>!a2.includes(i))
    .concat(a2.filter(i=>!a1.includes(i)))
}
https://jsfiddle.net/Stalk/7h5ahq5k/9/

A
Anton Shamanov, 2015-07-13
@SilenceOfWinter

Alternatively, you can serialize and compare the strings with the banal ==

D
Dima, 2020-12-26
@Fedechkin

I'm just starting to learn. For me, this code format is more understandable. Maybe someone will help. Added sorting from smallest to largest and vice versa.

var 
a1 = [1,2,3,99,88,77,89,-99,-199]
a2 = [1,2,3,8,89,9,-99,6,-77]

function sortMyArray(a,b){
 return   b - a;
}
function sortMyArrayR(a,b){
 return   a - b;
}

function comparison () {
   return a1.filter(i=>a2.indexOf(i)<0).concat(a2.filter(i=>a1.indexOf(i)<0))
}

write.innerHTML += "["+comparison(a1,a2).sort(sortMyArray)+"]";
arr.innerHTML +=  "["+ a1.sort(sortMyArray).toString()+"] \t["+a2.toString()+"]"
writeRev.innerHTML += "["+comparison(a1,a2).sort(sortMyArrayR)+"]";

<p id="arr"></p>
    <p id="write">
        compare:
    </p>
    <p id="writeRev">
        compareReverse:
    </p>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question