首页 > 编程语言 >JavaScript object array sort by string bug All In One

JavaScript object array sort by string bug All In One

时间:2024-05-16 10:21:23浏览次数:31  
标签:sort arr apple string object fruit type name

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 = '') => {
  const sortKeys = arr.map(obj => obj[key]).sort();
  console.log(`sortKeys =`, JSON.stringify(sortKeys));
  let result = [];
  for(let sortKey of sortKeys) {
    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"]'

(

标签:sort,arr,apple,string,object,fruit,type,name
From: https://www.cnblogs.com/xgqfrms/p/18195429

相关文章

  • [Paper Reading] PETR: Position Embedding Transformation for Multi-View 3D Object
    PETR:PositionEmbeddingTransformationforMulti-View3DObjectDetectionPETR:PositionEmbeddingTransformationforMulti-View3DObjectDetection时间:22.07机构:MegviiTL;DR一种多目3D目标检测的方法,主体思想是将3D坐标信息编码到2D图像特征,产生3Dawaredfeatur......
  • JavaScript Object valueOf & toString All In One
    JavaScriptObjectvalueOf&toStringAllInOneclassArrayWrapper{arr:number[];constructor(nums:number[]){this.arr=nums;}//✅改写Object内置方法valueOf,返回一个number整数//❓object相加(本质上是object序列化后的string......
  • Bear and String Distance
    传送锚点:codeforces.comCopy426bearoutputroarinput27afoutputdbinput31000heyoutput-1思路此题答案不限有点类似贪心,每一步都要做到最佳,将k不断变小code#include<iostream>#include<vector>#include<algorithm>#include<cstring>usingnamesp......
  • Mura CMS processAsyncObject SQL注入漏洞
    MuraCMSprocessAsyncObjectSQL注入漏洞漏洞描述该漏洞允许攻击者在某些API请求中注入恶意SQL代码,来访问或修改数据库信息,甚至可能获得对系统的完全控制,主要危害包括未授权访问敏感数据以及可能对系统完整性造成的损害Fofa:body="PoweredbyMuraCMS"POCPOST/index.cfm......
  • LeetCode 1915. Number of Wonderful Substrings
    原题链接在这里:https://leetcode.com/problems/number-of-wonderful-substrings/description/题目:A wonderful stringisastringwhere atmostone letterappearsan odd numberoftimes.Forexample, "ccjjc" and "abab" arewonderful,but "ab&......
  • (MEGA详解)Memory enhanced global-local aggregation for video object detection (CVPR
    在视频中检测物体和在图像中检测物体的最大区别在于:信息存在于时间维度中。视频中孤立的帧可能会出现运动模糊、遮挡或失焦等问题,自然可以想到从整个视频中寻找线索来识别物体。当我们无法确定一个目标的类别时,我们会从其它帧中寻找一个与当前目标具有高度语义相似性的独特目标,并......
  • String、StringBuffer、StringBuilder的区别
    在Java中,`String`、`StringBuffer`、和`StringBuilder`都是用于处理字符串的类,但它们之间存在一些关键差异,主要涉及可变性、线程安全性和性能:1.String:-不可变性:`String`对象一旦被创建,其内容就不能改变。任何对`String`的操作,比如拼接、替换等,都会返回一个新的`String`对象,而原......
  • String、StringBuffer、StringBuilder的区别
    在Java中,`String`、`StringBuffer`、和`StringBuilder`都是用于处理字符串的类,但它们之间存在一些关键差异,主要涉及可变性、线程安全性和性能:1.String:-不可变性:`String`对象一旦被创建,其内容就不能改变。任何对`String`的操作,比如拼接、替换等,都会返回一个新的`String`对象,而原......
  • LeetCode 1287. Element Appearing More Than 25% In Sorted Array
    原题链接在这里:https://leetcode.com/problems/element-appearing-more-than-25-in-sorted-array/description/题目:Givenanintegerarray sorted innon-decreasingorder,thereisexactlyoneintegerinthearraythatoccursmorethan25%ofthetime,returnthat......
  • java.lang.IllegalArgumentException: Invalid value type for attribute 'factoryBea
    简介前排提示:这个错误一般是由于Spring新版本导致的与其他框架不兼容现象,解决办法一般是升级其他框架版本。使用springboot-3.2.5和myabtis-plus-3.5.0搭建开发环境时,启动Springboot程序时报错,报错信息:点击查看代码java.lang.IllegalArgumentException:Invalidvalu......