[英]What am I doing wrong while trying to sort this array?
Need to sort an array of objects based on a particular value in that object.需要根据 object 中的特定值对对象数组进行排序。
const obj = [
{
field: "FULL_NAME",
required: "Y"
},
{
name: "EMAIL",
required: "N"
},
{
name: "ADDRESS",
required: "N"
},
{
name: "NUMBER",
required: "Y"
},
]
I want to sort this array in a way that fields with required 'Y' come first.我想以需要“Y”的字段排在第一位的方式对这个数组进行排序。
Tried to write a comparison function like this:试着像这样写一个比较 function :
const obj = [ { field: "FULL_NAME", required: "Y" }, { name: "EMAIL", required: "N" }, { name: "ADDRESS", required: "N" }, { name: "NUMBER", required: "Y" }, ]; const compare = (a, b) => { if(a.required === "Y" && b.required === "N"){ return 1 } if(a.required === "N" && b.required === "Y"){ return -1 } return 0; } console.log(obj.sort(compare));
How do I fix it so it works?我该如何修复它才能正常工作?
You have the 1
and -1
backwards.你有
1
和-1
倒退。 -1
means the first element argument is sorted first, and 1
means the second element argument is sorted first. -1
表示第一个元素参数首先排序, 1
表示第二个元素参数首先排序。 See the compareFunction
/ sort order table at the Array.prototype.sort()
article :请参阅
Array.prototype.sort()
文章中的compareFunction
/ 排序顺序表:
compareFunction(a, b) return value ![]() compareFunction(a, b) 返回值 |
sort order![]() |
---|---|
> 0 |
sort b before a ![]() b 在a 之前 |
< 0 |
sort a before b ![]() b 之前排序a |
=== 0 |
keep original order of a and b ![]() a 和b 的原始顺序 |
const obj = [ { field: "FULL_NAME", required: "Y" }, { name: "EMAIL", required: "N" }, { name: "ADDRESS", required: "N" }, { name: "NUMBER", required: "Y" }, ]; const compare = (a, b) => { if(a.required === "Y" && b.required.== "Y"){ return -1 } if(a.required;== "Y" && b.required === "Y"){ return 1 } return 0. } console;log(obj.sort(compare));
Shortest version using ES6使用 ES6 的最短版本
obj.sort((a,b) => a.required > b.required ? -1: 1);
Reference: Sort objects in an array alphabetically on one property of the array参考:在数组的一个属性上按字母顺序对数组中的对象进行排序
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.