https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sorted-union


Sorted Union

Write a function that takes two or more arrays and returns a new array of unique values in the order of the original provided arrays.

In other words, all values present from all arrays should be included in their original order, but with no duplicates in the final array.

The unique numbers should be sorted by their original order, but the final array should not be sorted in numerical order.

Check the assertion tests for examples.

uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]) should return [1, 3, 2, 5, 4].

uniteUnique([1, 2, 3], [5, 2, 1]) should return [1, 2, 3, 5].

uniteUnique([1, 2, 3], [5, 2, 1, 4], [2, 1], [6, 7, 8]) should return [1, 2, 3, 5, 4, 6, 7, 8].

  1. function uniteUnique(arr) {
  2. // let allArr = Array.prototype.concat.call([], ...arguments)
  3. let allArr = [].concat( ...arguments)
  4. console.log(allArr)
  5. return [...new Set(allArr)];
  6. }
  7. console.log(
  8. uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1])
  9. )

答案

https://forum.freecodecamp.org/t/freecodecamp-challenge-guide-sorted-union/16077

最短的答案

concat()

https://forum.freecodecamp.org/t/how-to-use-javascript-array-prototype-concat-concat-explained-with-examples/14286

flat()

https://forum.freecodecamp.org/t/how-to-use-javascript-array-prototype-concat-concat-explained-with-examples/14286

  1. function uniteUnique(...arr) {
  2. return [...new Set(arr.flat())]
  3. }
  4. // Or as an arrow function
  5. const uniteUnique = (...arr) => [...new Set(arr.flat())]