Reputation: 1626
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.
Upvotes: 1
Views: 119
Reputation: 11930
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;
}
Upvotes: 1
Reputation: 386540
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; }
Upvotes: 2