Answer the question
In order to leave comments, you need to log in
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
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])
}
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/
Alternatively, you can serialize and compare the strings with the banal ==
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 questionAsk a Question
731 491 924 answers to any question