user3438917 - 1 year ago 71
Javascript Question

Function to create array of arrays in javascript

Given an array with characters such as ["A","P","P","L","E","S","A","R","E"], I'm trying to create a function that will loop over the elements in the array, and create an array for each character, which will then be put into a master array. The master array will end up looking like

`[["A"],["P","P"],["L"],["E"],["S"],["A"],["R"],["E"]`
at the end, using a comparator function to check values
`(a,b) => a == b`
. Essentially, it needs to check each successive letter, and if they are the same, group into their own array within the master. The two A's should not be grouped together, since they aren't successive.

``````var arr = ["A","P","P","L","E"];
var master = [];
arr.sort(function(a,b){
for(var i = 0; i <= arr.length; i++){
compare each element to its successor. if successor is the same, create array of like elements ["A"],["C","C"],["B"] within final array
if(i + 1 == i){
master.push(i);
}
}
});
``````

You might do as follows;

``````var arr = ["A","P","P","L","E"],
result = arr.reduce((p,c) => {var fi = p.findIndex(a => a[0] === c);
fi === -1 ? p.push([c]) : p[fi].push(c);
return p;
},[]);
console.log(result);``````

As per the grouping only the sequential duplicates the following should do;

``````var      arr = ["A","P","P","L","E","S","A","R","E"],
stickTheSame = a => a.reduce((p,c) => (p[p.length-1][0] === void 0 ||
p[p.length-1][0] === c      ? p[p.length-1].push(c)
: p.push([c]),
p),[[]]);
console.log(JSON.stringify(stickTheSame(arr)));``````

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download