-1

I'm trying to turn a list into a list of lists. In this case I have a list similar to the following: a = [ 1, 1, 1, 2, 3, 3] and I would like to separate the same items for another list, like: a = [[1, 1, 1] ; [2] ; [3, 3]]

 let b = this.a.filter((element, index) => {
                 return this.a.indexOf(element) === index;
             });

I tried using splice and filter, but without success. I was only able to create a list with different values... b=[1,2,3] Is there any solution?

2 Answers 2

2

There are many ways to do this, including the experimental (generally unsupported) group() method.

One simple solution is to use reduce(), something like this, to iterate over the array and construct a new, nested one:

let a = [ 1, 1, 1, 2, 3, 3 ];
let b = a.reduce(
    (acc, each) => {
        let index = acc.length - 1;
        if (acc.length && acc[index][0] == each) {
            acc[index].push(each);
        } else {
            acc.push([each]);
        }
        return acc;
    },
    []
);

// Yields [[1,1,1],[2],[3,3]]

2
  • Haha, yeah, many ways indeed :D
    – sfdcfox
    Jul 22, 2022 at 2:45
  • @sfdcfox your solution is lovely but took me a couple of minutes to work out! Love the use of comma operator.
    – David Reed
    Jul 22, 2022 at 4:36
1

For normal browsers, you probably want Array.prototype.reduce.

let group = (values) =>
Object.values(  // Convert { a: b } to just [b]
  values.reduce(
    (p, v) => ( // p = previous value, v = next value
      (p[v] ||= []), // Assign p[v] a new array if not yet set
      p[v].push(v), // Add v to this array
      p), // Return p for next iteration
    {}) // Initial state object for reduce
);

Which will return an Array of arrays with all the same value.

let source = [1, 1, 1, 2, 3, 3];
group(source); // [[1, 1, 1], [2], [3, 3, 3]]

There's are two experimental methods called Array.prototype.group and Array.prototype.groupToMap that would fundamentally output the same results ({ 1: [1,1,1], 2: [2], 3: [3,3,3] }), but isn't available without polyfills except in Firefox Nightly, so you're better off having a handy function like this if you find yourself needing this sort of grouping often.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .