簡體   English   中英

根據字符串對對象數組進行排序

[英]Sort an array of objects based on string

我有一個具有兩個屬性 id 和 fileName 的對象數組。 我想根據文件的數量對數組進行排序。 例如我有數組:

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

我希望它像這樣排序:

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

      },

為了支持多位數字,您最終需要類似“自然”排序的東西,並結合從每個fileName中獲取文件名:

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

您可以使用sort -Function 對這樣的列表進行排序,拆分名稱並將第一個數字解析為浮點數:

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

這將返回:

[
    {
        "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
    }
]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM