Reconstruct array javascript index-based

3609 views javascript
1

suppose I have an array in JavaScript as written below :

Array:[  
    ["0", "Grape"],["0", "Orange"],["1", "Mango"],["2", "Strawberry"],
    ["2", "Banana"],["3", "Watermelon"]
]

that I want to reconstruct as :

Array:[  
    ["Grape", "Orange"],["Mango"],["Strawberry", "Banana"],["Watermelon"]
]

The numbers in initial array acts as indexes of fruits' data in reconstructed array. So, Grape and Orange are placed in index 0, Mango in index 1, and so on. How do I achieved this? Thank you.

answered question

3 Answers

8

Use Array.reduce and Object.assign

let arr1 = [["0", "Grape"],["0", "Orange"],["1", "Mango"],["2", "Strawberry"],["2", "Banana"],["3", "Watermelon"]];

let arr2 = arr1.reduce((a,c) => Object.assign(a, {[c[0]]:(a[c[0]] || []).concat(c[1])}), []);
console.log(arr2);

posted this
11

You can use reduce and new Map as accumulator.

let arr = [["0", "Grape"],["0", "Orange"],["1", "Mango"],["2", "Strawberry"],["2", "Banana"],["3", "Watermelon"]];

let result = [...arr.reduce((c, [k, v]) => {
  if (!c.has(k)) c.set(k, []);
  c.get(k).push(v);
  return c;
}, new Map()).values()];

console.log(result);


Can be written in one line by:

let arr = [["0", "Grape"],["0", "Orange"],["1", "Mango"],["2", "Strawberry"],["2", "Banana"],["3", "Watermelon"]];

let result = [...arr.reduce((c, [k, v]) => c.set(k, !c.has(k) ? [v] : c.get(k).concat(v)), new Map()).values()];

console.log(result);

posted this
1

a is your initial array: Here I supposed that indices start at 0, are integers and are sorted.

a = [["0", "Grape"],["0", "Orange"],["1", "Mango"],["2", "Strawberry"],["2", "Banana"],["3", "Watermelon"]]
b=[];
for (i in a) {
    if (a[i][0] >= b.length)
        b.push([]);

    (b[b.length-1]).push(a[i][1]);
}

posted this

Have an answer?

JD

Please login first before posting an answer.