admin管理员组文章数量:1333210
Question
Compare two arrays and return a new array with any items only found in one of the two given arrays, but not both. In other words, return the symmetric difference of the two arrays.
Note You can return the array with its elements in any order.
Professional Developers Answer
function diffArray(arr1, arr2) {
return [...diff(arr1, arr2), ...diff(arr2, arr1)];
function diff(a, b) {
return a.filter(item => b.indexOf(item) === -1);
}
}
Question
Compare two arrays and return a new array with any items only found in one of the two given arrays, but not both. In other words, return the symmetric difference of the two arrays.
Note You can return the array with its elements in any order.
Professional Developers Answer
function diffArray(arr1, arr2) {
return [...diff(arr1, arr2), ...diff(arr2, arr1)];
function diff(a, b) {
return a.filter(item => b.indexOf(item) === -1);
}
}
My Question
I don't understand how this code operates. In particular I have never seen the spread operator used like this. Please could you explain how this works?
Share Improve this question asked Apr 27, 2020 at 15:58 AndrewNeedsHelpAndrewNeedsHelp 4155 silver badges16 bronze badges 2- 2 it is just concatenating two arrays together – epascarello Commented Apr 27, 2020 at 16:01
-
Professional developer that uses spread syntax but not
includes
orSet
? .oO – Bergi Commented Apr 27, 2020 at 16:35
2 Answers
Reset to default 6It is just a fancy way to concat two arrays together. This is how it looks if you did not use the spread operator
function diffArray(arr1, arr2) {
function diff(a, b) {
return a.filter(item => b.indexOf(item) === -1);
}
var diff1 = diff(arr1, arr2) // [0, 1]
var diff2 = diff(arr2, arr1) // [5, 6]
return [].concat(diff1, diff2) // [0, 1, 5, 6]
}
var res = diffArray([0,1,2,3,4], [2,3,4,5,6])
console.log(res)
The spread operator used on an array takes the elements out of the array and puts them directly into the data structure that contains them. So if A = [1,2,3]
and B = [4,5,6]
then [...A, ...B] === [1,2,3,4,5,6]
. Without the spread operator, they would be [[1,2,3], [4,5,6]]
.
本文标签:
版权声明:本文标题:Find the Difference Between Two Arrays (Javascript Algorithm) + Funky Use of the Spread Operator - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742281136a2446105.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论