Ali
Ali

Reputation: 21

Return a nested array

I need help making this function after taking an array and another array (duplicate) that has just the numbers that are duplicated in the first array (for example array=[1,2,3,1,2,3,4,5,6,6], duplicate=[1,2,3,6]).

I want it to return an array as follow: finalArray1=[[1,1],[2,2],[3,3],4,5,[6,6]].

let input = [1,2,4,591,392,391,2,5,10,2,1,1,1,20,20];

let sortArray = array => {
  return array.sort(function(a, b) {
    return a - b;});
}

function findDuplicates(data) {

  let duplicate = [];

  data.forEach(function(element, index) {

    // Find if there is a duplicate or not
    if (data.indexOf(element, index + 1) > -1) {

      // Find if the element is already in the duplicate array or not
      if (duplicate.indexOf(element) === -1) {
        duplicate.push(element);
      }
    }
  });

  return duplicate; 
}

let newArray = (array, duplicate) => { 

  for( var i = 0; i < 3; i++ ){
    for( var j = 0; j < 15; j++ ){
      if( duplicate[i] == array[j] ){
        let finalArray = new array().push(array[j]);
      }
    }
    return finalArray;
  }
}

Upvotes: 1

Views: 426

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386654

You could take a Map and return in original order.

The map takes the items in insertation order, which means all item are later in original order. If a key exists, it createsd an array with the value. Otherwise just the item form the array is taken as value for the map.

At the end take only the values from the map and create an array of it.

let input = [1, 2, 4, 591, 392, 391, 2, 5, 10, 2, 1, 1, 1, 20, 20],
    result = Array.from(input
        .reduce((m, v) => m.set(v, m.has(v) ? [].concat(m.get(v), v) : v), new Map)
        .values()
    );

console.log(result);

A more traditional approach

let input = [1, 2, 4, 591, 392, 391, 2, 5, 10, 2, 1, 1, 1, 20, 20],
    result = input
        .sort((a, b) => a -b)
        .reduce((r, v, i, a) => {
            if (a[i - 1] !== v && v !== a[i + 1]) r.push(v); // check if unique
            else if (a[i - 1] !== v) r.push([v]);            // check left element
            else r[r.length - 1].push(v);
            return r;
        }, []);

console.log(result);

Upvotes: 2

norbitrial
norbitrial

Reputation: 15166

I think the following can work for you:

const input = [1,2,4,591,392,391,2,5,10,2,1,1,1,20,20];

const inOrder = input.sort((a, b) => a - b);
const unique = inOrder.reduce((a, c) => {
  const found = a.find(e => e.includes(c));      
  if (found) found.push(c);
  else a.push([c]);      
  return a;
}, []);
const result = unique.map(e => e.length > 1 ? e : e[0]);

console.log(result);

I hope this helps!

Upvotes: 0

Related Questions