Human A. Human A. - 1 year ago 63
Javascript Question

Sort a javascript array into nested arrays based on values

I have an array of file names like so:

var filesArray = [

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:


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
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 Source

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);
}, new Map);

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

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