I have an array of objects with two attributes, id and fileName. I want to sort the array based on the numbers of the files. For example I have the array:
let array = [
{
fileName: "5.4 Hello world",
id: 2
},
{
fileName: "1.1 String",
id: 5
},
{
fileName: "3.2 Sort ",
id: 1
},
{
fileName: "4. This is a string",
id: 4
},
And I want it to be sorted like this:
array = [
{
fileName: "1.1 String",
id: 5
},
{
fileName: "3.2 Sort ",
id: 1
},
{
fileName: "4. This is a string",
id: 4
},
{
fileName: "5.4 Hello world",
id: 2
},
To support multidigit numbers, you would eventually need something like "natural" sort, and that in combination with fetching the fileName
from each object:
const collator = new Intl.Collator(undefined, {numeric: true, sensitivity: 'base'}); const natSort = array => array.sort((a, b) => collator.compare(a.fileName, b.fileName)); // Example use const array = [{fileName: "5.4 Hello world", id: 2},{fileName: "1.1 String",id: 5},{fileName: "3.2 Sort ",id: 1},{fileName: "4. This is a string",id: 4},]; const result = natSort(array); console.log(result);
You can sort a list like this with the sort -Function, split the name and parse the first number as float:
const list = [
{
fileName: "5.4 Hello world",
id: 2
},
{
fileName: "1.1 String",
id: 5
},
{
fileName: "3.2 Sort ",
id: 1
},
{
fileName: "4. This is a string",
id: 4
},
]
list.sort((a, b) => {
const aIdx = parseFloat(a.fileName.split(" ")[0])
const bIdx = parseFloat(b.fileName.split(" ")[0])
return (aIdx > bIdx) ? 1 : -1
})
console.log(JSON.stringify(list, null, 4))
This will return:
[
{
"fileName": "1.1 String",
"id": 5
},
{
"fileName": "3.2 Sort ",
"id": 1
},
{
"fileName": "4. This is a string",
"id": 4
},
{
"fileName": "5.4 Hello world",
"id": 2
}
]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.