How to convert a list to a list of lists in Javascript?

594    Asked by dipesh_9001 in Salesforce , Asked on May 1, 2023
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?

Answered by Diya tomar

For normal browsers, to convert a list to a list of lists in Javascript, 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.



Your Answer

Interviews

Parent Categories