1

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.

0

2 Answers 2

2

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; }

Sign up to request clarification or add additional context in comments.

2 Comments

Do you like my version? And can i use your css on my anwer :)?
yes, you can use the css. your answer needs an additional loop for the result.
1

var filesArray = ["120.png", "120s.png", "120t.jpg", "169.png", "169r.jpg", "169s.jpg", "169t.jpg", "170.png", "170r.jpg", "170s.jpg", "170t.jpg"];
var result = [];
var obj = filesArray.reduce(function(prev, curr, index, array) {
  var rawName = curr.match(/[0-9]/g);
  if (rawName.length) {
    var name = rawName.join('');
    if (prev[name]) {
      prev[name].push(curr);
    } else {
      prev[name] = [curr];
    }
  }
  return prev
}, {});

Object.keys(obj).forEach(function(key) {
  result.push(obj[key]);
});
console.log(result);
.as-console-wrapper {
  max-height: 100% !important;
  top: 0;
}
.as-console-row,
.as-console-row-code {
  background-color: #fff!important;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.