JavaScript object array sort by string bug All In One

xgqfrms發表於2024-05-16

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"}] ✅

image

demos

let arr = ['ab', 'ac', 'cc'];
JSON.stringify(arr.sort());
// '["ab","ac","cc"]'

(🐞 反爬蟲測試!打擊盜版⚠️)如果你看到這個資訊, 說明這是一篇剽竊的文章,請訪問 https://www.cnblogs.com/xgqfrms/ 檢視原創文章!

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



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 釋出文章使用:只允許註冊使用者才可以訪問!

原創文章,版權所有©️xgqfrms, 禁止轉載 🈲️,侵權必究⚠️!


相關文章