-2

I am trying to find a way to soolve this question using reducer write a function called merge that takes one or more arrays as parameters and returns the merged togerher with all dublicates removed and with the values sorted in ascending order

var a = ["alpha", "charlie", "delta"]
var b = ["bravo", "delta"]
var c = "["golf", "delta"]
var d = ["foxtrot", "delta", "echo", "alpha"]


merge(a,b) returns ["alpha", "bravo", "charlie", "delta"]
merge(a,b,c,d) returns ["alpha","bravo","charlie","delta","echo","foxtrot","golf"]
var a = ["alpha", "charlie", "delta"]
var b = ["bravo", "delta"]
var c = "["golf", "delta"]
var d = ["foxtrot", "delta", "echo", "alpha"]

function merge(...arr){
   const mergedArr = [...arr];
   const sortArr = mergetAr.sort();
   const reducedArr = sortArr.reduce((arr, sortArr) => {
    return 
},[])
}
merge(a,b)
Maurya
  • 41
  • 3

3 Answers3

2

You can flatten the array and use Set to filter out the duplicates.

var a = ["alpha", "charlie", "delta"]
var b = ["bravo", "delta"]

function merge(...arr){
   const sortArr = [...new Set(arr.flat())].sort();
   console.log('sortArr', sortArr);
}
merge(a,b);
Ayaz
  • 2,111
  • 4
  • 13
  • 16
  • `[...arr].flat()` ... so exactly like `arr.flat()` - why not a single line ... `const merge = (...arr) => [...new Set(arr.flat())].sort();` FTW – Bravo May 06 '22 at 06:41
0

Instead of directly taking the arguments, pass them in an array. That will allow you to loop through n number of arguments without any restriction as follows:

function merge(arrayOfArrays) {
  const set = new Set(); // to remove duplicates
  for (const array of arrayOfArrays) {
    set.add(...array);
  }
  return [...set].sort();
}

Working snippet:

var a = ["alpha", "charlie", "delta"];
var b = ["bravo", "delta"];
var c = ["golf", "delta"];
var d = ["foxtrot", "delta", "echo", "alpha"];

function merge(arrayOfArrays) {
  const set = new Set(); // to remove duplicates
  for (let array of arrayOfArrays) {
    array.forEach(item => set.add(item))
  }

  return [...set].sort();
}

console.log(merge([a, b, c, d]));
Aneesh
  • 1,720
  • 4
  • 14
-1

The solution goes below.

 var a = ["alpha", "charlie", "delta"]
         var b = ["bravo", "delta"]
         var c = ["golf", "delta"]
         var d = ["foxtrot", "delta", "echo", "alpha"]
         var all_array = a.concat(b).concat(c).concat(d); //combine all arrays
        

         var uniq_array = [...new Set(all_array)]; // remove all duplicates

         uniq_array = uniq_array.sort(); //soert the unique array in ascending order
         console.log(uniq_array)
Albert Alberto
  • 801
  • 8
  • 15
  • instead of "merge", you can use the inbuilt " concat" function to merge the arrays. – Albert Alberto May 06 '22 at 06:33
  • so, you'd have to have two code blocks, almost identical, except one does a and b and the other does a, b, c and d - that's what **functions** are for, so you don't repeat yourself – Bravo May 06 '22 at 06:34