如何对具有动态属性的对象数组进行排序?

huangapple go评论58阅读模式
英文:

How to sort an array of objects with dynamic property?

问题

我正在尝试对对象数组进行排序排序将根据动态属性进行

我有一个数组

    const fruitDetails = [
      {item: "Berry", qty: "651042446", stockDate: "2021-09-20"},
      {item: "Apple", qty: "23222", stockDate: "2023-08-10"},
      {item: "Kiwi", qty: "132345", stockDate: "2022-10-23"}
    ];

现在排序可以基于itemqty或stockDate进行

用于对此对象数组进行动态属性排序的函数

    function sortedData(column) {
      return fruitDetails.sort((a, b) => {
         if (a[column].toLowerCase() > b[column].toLowerCase()) {
           return 1;
         }
         if (a[column].toLowerCase() < b[column].toLowerCase()) {
           return -1;
         }
         return 0;
      });
    }

    
    console.log(sortedData("item"));
    console.log(sortedData("qty"));
    console.log(sortedData("stockDate"));


如果您检查控制台输出item和stockDate的排序值是正确的但qty的排序值是错误的

以下是qty的控制台输出

    [{
      item: "Kiwi",
      qty: "132345",
      stockDate: "2022-10-23"
    }, {
      item: "Apple",
      qty: "23222",
      stockDate: "2023-08-10"
    }, {
      item: "Berry",
      qty: "651042446",
      stockDate: "2021-09-20"
    }]

qty值23222小于132345因此Apple应该是第一Kiwi是第二Berry是第三

我在此添加了[jsfiddle链接][1]以供参考
请告诉我我在这里做错了什么谢谢 :)


  [1]: https://jsfiddle.net/Ln7u5zqb/
英文:

I am trying to sort an array of objects and the sorting will be done based on property which will be dynamic

I have an array

const fruitDetails = [
{item: &quot;Berry&quot;, qty: &quot;651042446&quot;, stockDate: &quot;2021-09-20&quot;},
{item: &quot;Apple&quot;, qty: &quot;23222&quot;, stockDate: &quot;2023-08-10&quot;},
{item: &quot;Kiwi&quot;, qty: &quot;132345&quot;, stockDate: &quot;2022-10-23&quot;}
];

Now the sorting could be of on item, qty or stockDate

A function to sort this array of objects with dynamic property

function sortedData(column) {
return fruitDetails.sort((a, b) =&gt; {
if (a[column].toLowerCase() &gt; b[column].toLowerCase()) {
return 1;
}
if (a[column].toLowerCase() &lt; b[column].toLowerCase()) {
return -1;
}
return 0;
});
}
console.log(sortedData(&quot;item&quot;));
console.log(sortedData(&quot;qty&quot;));
console.log(sortedData(&quot;stockDate&quot;));

If you check the console output the sorted value for item and stockDate is correct but the qty sorted value is incorrect.

This is the console output for qty:

[{
item: &quot;Kiwi&quot;,
qty: &quot;132345&quot;,
stockDate: &quot;2022-10-23&quot;
}, {
item: &quot;Apple&quot;,
qty: &quot;23222&quot;,
stockDate: &quot;2023-08-10&quot;
}, {
item: &quot;Berry&quot;,
qty: &quot;651042446&quot;,
stockDate: &quot;2021-09-20&quot;
}]

The qty value 23222 is smaller than the 132345 so Apple should be 1st, Kiwi 2nd and Berry 3rd.

I am adding the jsfiddle link for reference.
Please let me know what I am doing wrong here, thank you 如何对具有动态属性的对象数组进行排序?

答案1

得分: 1

const fruitDetails = [{
    item: "Berry",
    qty: "651042446",
    stockDate: "2021-09-20"
  },
  {
    item: "Apple",
    qty: "23222",
    stockDate: "2023-08-10"
  },
  {
    item: "Kiwi",
    qty: "132345",
    stockDate: "2022-10-23"
  }
];

function filters(key) {
  return fruitDetails.sort((a, b) => {
    if (key === 'item') {
      return a[key].localeCompare(b[key])
    } else if (key === 'qty') {
      return a[key] - (b[key]);
    } else if (key === 'stockDate') {
      return new Date(a[key]) - new Date((b[key]));
    }
  })
}
console.log(filters("item"));
console.log(filters("qty"));
console.log(filters("stockDate"));
英文:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const fruitDetails = [{
item: &quot;Berry&quot;,
qty: &quot;651042446&quot;,
stockDate: &quot;2021-09-20&quot;
},
{
item: &quot;Apple&quot;,
qty: &quot;23222&quot;,
stockDate: &quot;2023-08-10&quot;
},
{
item: &quot;Kiwi&quot;,
qty: &quot;132345&quot;,
stockDate: &quot;2022-10-23&quot;
}
];
function filters(key) {
return fruitDetails.sort((a, b) =&gt; {
if (key === &#39;item&#39;) {
return a[key].localeCompare(b[key])
} else if (key === &#39;qty&#39;) {
return a[key] - (b[key]);
} else if (key === &#39;stockDate&#39;) {
return new Date(a[key]) - new Date((b[key]));
}
})
}
console.log(filters(&quot;item&quot;));
console.log(filters(&quot;qty&quot;));
console.log(filters(&quot;stockDate&quot;));

<!-- end snippet -->

答案2

得分: 1

你可以使用正则表达式来测试数字,然后在排序数字时,就像通常排序数字一样,减去从字符串转换的数字。否则,使用String#localCompare方法如下;以提供的格式的字符串和“日期字符串”应该可以使用.localeCompare()进行排序:

const fruitDetails = [
  {item: "Berry", qty: "651042446", stockDate: "2021-09-20"},
  {item: "Apple", qty: "23222", stockDate: "2023-08-10"},
  {item: "Kiwi", qty: "132345", stockDate: "2022-10-23"}
];

function sortedData(column) { //升序
  return fruitDetails.sort((a, b) => {
     const numRe = /^[0-9]*$/;
     if (numRe.test(a[column]) && numRe.test(b[column])) {
         return +a[column] - +b[column];
     } else {
         return a[column].localeCompare(b[column]);
     }
  });
}

console.log(sortedData("item"));
console.log(sortedData("qty"));
console.log(sortedData("stockDate"));

【注意】:我已经帮你翻译好了,不需要回答。

英文:

You can use regular expressions to test for numbers, then you would subtract the numbers (converted from strings) as you normally would when sorting numbers. Otherwise use the String#localCompare method as follows; strings and "date strings" in the format provided should sort fine with .localeCompare():

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const fruitDetails = [
{item: &quot;Berry&quot;, qty: &quot;651042446&quot;, stockDate: &quot;2021-09-20&quot;},
{item: &quot;Apple&quot;, qty: &quot;23222&quot;, stockDate: &quot;2023-08-10&quot;},
{item: &quot;Kiwi&quot;, qty: &quot;132345&quot;, stockDate: &quot;2022-10-23&quot;}
];
function sortedData(column) { //ascending order
return fruitDetails.sort((a, b) =&gt; {
const numRe = /^[0-9]*$/;
if (numRe.test(a[column]) &amp;&amp; numRe.test(b[column])) {
return +a[column] - +b[column];
} else {
return a[column].localeCompare(b[column]);
}
});
}
console.log(sortedData(&quot;item&quot;));
console.log(sortedData(&quot;qty&quot;));
console.log(sortedData(&quot;stockDate&quot;));

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年7月12日 22:56:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76671932.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定