最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Find the Difference Between Two Arrays (Javascript Algorithm) + Funky Use of the Spread Operator - Stack Overflow

programmeradmin2浏览0评论

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 or Set? .oO – Bergi Commented Apr 27, 2020 at 16:35
Add a ment  | 

2 Answers 2

Reset to default 6

It 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]].

发布评论

评论列表(0)

  1. 暂无评论