JavaScript object array sort by string bug All In One
JavaScript object array sort by string bug All In One
bug
// pure strings array, sort OK ✅
let arr = ["banana", "strawberry", "apple"];
JSON.stringify(arr.sort());
// '["apple","banana","strawberry"]'
// object array, using string key sort error ❌
let arr = [
{
"type": "fruit",
"name": "banana"
},
{
"type": "fruit",
"name": "strawberry"
},
{
"type": "fruit",
"name": "apple"
}
];
const sortName = (obj) => obj.name;
JSON.stringify(arr.sort((a, b) => sortName(a) - sortName(b) > 0 ? 1 : -1));
// '[{"type":"fruit","name":"apple"},{"type":"fruit","name":"strawberry"},{"type":"fruit","name":"banana"}]' ❌
JSON.stringify(arr.sort(a => sortName(a)));
// '[{"type":"fruit","name":"apple"},{"type":"fruit","name":"strawberry"},{"type":"fruit","name":"banana"}]' ❌
solutions
let arr = [
{
"type": "fruit",
"name": "banana"
},
{
"type": "fruit",
"name": "strawberry"
},
{
"type": "fruit",
"name": "apple"
}
];
const sortObjectArrayByStringKey = (arr = [], key = '') => {
// 1. sort string keys ✅
const sortKeys = arr.map(obj => obj[key]).sort();
console.log(`sortKeys =`, JSON.stringify(sortKeys));
let result = [];
for(let sortKey of sortKeys) {
// 2. custom order objetcs with sortKey 🚀
result.push(arr.find(obj => obj[key] === sortKey))
}
console.log(`result =`, JSON.stringify(result));
return result;
}
sortObjectArrayByStringKey(arr, 'name');
// sortKeys = ["apple","banana","strawberry"] ✅
// result = [{"type":"fruit","name":"apple"},{"type":"fruit","name":"banana"},{"type":"fruit","name":"strawberry"}] ✅
demos
let arr = ['ab', 'ac', 'cc'];
JSON.stringify(arr.sort());
// '["ab","ac","cc"]'
let arr =[
{
"type": "fruit",
"name": "banana"
},
{
"type": "candy",
"name": "twix"
},
{
"type": "vegetable",
"name": "broccoli"
},
{
"type": "vegetable",
"name": "carrot"
},
{
"type": "fruit",
"name": "strawberry"
},
{
"type": "candy",
"name": "kitkat"
},
{
"type": "fruit",
"name": "apple"
}
];
const sortObjectArrayByStringKey = (arr = [], key = '') => {
// 1. sort string keys ✅
const sortKeys = arr.map(obj => obj[key]).sort();
console.log(`sortKeys =`, JSON.stringify(sortKeys));
let result = [];
for(let sortKey of sortKeys) {
// 2. custom order objetcs with sortKey 🚀
result.push(arr.find(obj => obj[key] === sortKey))
}
console.log(`result =`, JSON.stringify(result));
return result;
}
// groups
function sortArrayOnOrder(arr, types, key) {
let result = [];
for(let type of types) {
let temp = arr.filter(obj => obj.type === type);
result.push(...sortObjectArrayByStringKey(temp, key));
}
console.log(`result =`, JSON.stringify(result));
return result;
}
sortArrayOnOrder(arr, ["fruit","candy","vegetable"], "name");
// result = [{"type":"fruit","name":"apple"},{"type":"fruit","name":"banana"},{"type":"fruit","name":"strawberry"},{"type":"candy","name":"kitkat"},{"type":"candy","name":"twix"},{"type":"vegetable","name":"broccoli"},{"type":"vegetable","name":"carrot"}]
https://stackoverflow.com/questions/14872554/sorting-on-a-custom-order
<!--
<details>
<summary>
</summary>
</details>
-->
## <div id="anti-crawler" style="color: red;"> (🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!</div>
## refs
https://dev.to/banesag/sorting-arrays-of-strings-in-javascript-2g11
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare
https://stackoverflow.com/questions/15084070/is-this-a-bug-in-array-sort
https://www.cnblogs.com/xgqfrms/p/11290367.html
https://www.cnblogs.com/xgqfrms/p/16002200.html
***
<div>
<a href="https://info.flagcounter.com/QIXi">
<img src="https://s11.flagcounter.com/count2/QIXi/bg_000000/txt_00FF00/border_FF00FF/columns_3/maxflags_12/viewers_0/labels_1/pageviews_1/flags_0/percent_1/" alt="Flag Counter" border="0">
</a>
</div>
***
<blockquote style="display: flex; flex-flow: column; align-items: center; justify-content: center; text-align: center; border: none;">
<h3><strong><span style="font-size: 16pt; color: #00ff00;">©xgqfrms 2012-<span data-uid="copyright-aside">2021</span></strong></span</h3>
<p><span style="font-size: 18pt; color: #00ff00;"><strong>www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!</strong></span></p>
<p><span style="font-size: 18pt; color: #00ff00;"><strong>原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!</strong></span></p>
</blockquote>
***
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/18195429
未经授权禁止转载,违者必究!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)
2023-05-16 How to use the Raspberry Pi and Python to control a DHT11 wet and temperate module All In One
2023-05-16 How to use the Raspberry Pi and Python to control a buzzer All In One
2023-05-16 上海外国语大学世界语言博物馆 All In One
2022-05-16 SwiftUI 父子 UI 组件之间通信 All In One
2022-05-16 Swift & SwiftUI delay code All In One
2022-05-16 SwiftUI & Xcode crashed error All In One
2022-05-16 Swift comments All In One