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

image

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

image

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>

***
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章