Human A. Human A. - 1 month ago 10
Javascript Question

Sort a javascript array into nested arrays based on values

I have an array of file names like so:

var filesArray = [
"120.png",
"120s.png",
"120t.jpg",
"169.png",
"169r.jpg",
"169s.jpg",
"169t.jpg",
"170.png",
"170r.jpg",
"170s.jpg",
"170t.jpg",
]


Using javascript (es5 or 6 or 7 does not matter since I am using babel) I would like to sort it into a nested array like so:

[
[
"120.png",
"120s.png",
"120t.jpg"
],
[
"170.png",
"170r.jpg",
"170s.jpg",
"170t.jpg"
]
]


I know that in order to find the same base names I have to run regex and I am already using
filesArray[i].slice(0, -4).replace(/[^0-9\.]/g, '') )


What I don't know however is how to run
array.sort
or
array.map
to get the final neste array.

By the way, it's long list of file names, and I would prefer the fastest most efficient way to do so without mutating the original array.

Answer

You could use a Map for grouping the items.

var filesArray = ["120.png", "120s.png", "120t.jpg", "169.png", "169r.jpg", "169s.jpg", "169t.jpg", "170.png", "170r.jpg", "170s.jpg", "170t.jpg"],
    grouped = [];

filesArray.forEach(function (a) {
    var key = a.slice(0, -4).replace(/[^0-9\.]/g, ''),
        array = this.get(key);

    if (!array) {
        array = [];
        this.set(key, array);
        grouped.push(array);
    }
    array.push(a);
}, new Map);

console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }