Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
413 views
in Technique[技术] by (71.8m points)

javascript - 基于具有不同数据类型的两个键以升序对对象数组进行排序(Sorting an array of objects in ascending order based on two keys having different datatypes)

I want to sort an array in ascending order based on two properties.(我想基于两个属性以升序对数组进行排序。)

I have following data array which looks like(我有以下数据数组看起来像) [ { id: 1, name: 'ABP', code: 1460, subCode: '0010' }, { id: 2, name: 'GKY', code: 1460, subCode: '0030' }, { id: 3, name: 'CPT', code: 1410, subCode: '0070' }, { id: 4, name: 'KLB', code: 1470, subCode: '0050' }, { id: 5, name: 'POL', code: 1430, subCode: '0050' }, { id: 6, name: 'FVB', code: 1410, subCode: '0050' }, ] I want to sort it like(我想排序) [ { id: 6, name: 'FVB', code: 1410, subCode: '0050' }, { id: 3, name: 'CPT', code: 1410, subCode: '0070' }, { id: 5, name: 'POL', code: 1430, subCode: '0050' }, { id: 1, name: 'ABP', code: 1460, subCode: '0010' }, { id: 2, name: 'GKY', code: 1460, subCode: '0030' }, { id: 4, name: 'KLB', code: 1470, subCode: '0050' }, ] I want to sort the array in ascending order based on code property and if same code exist for multiple items then I want to sort it based on subCode of the code property.(我想基于code属性以升序对数组进行排序,如果相同的code存在多个项目,那么我想基于code属性的subCode进行排序。) Problem I am facing here is, subCode is in string and code is in number.(我在这里面临的问题是, subCode在字符串中,而code在数字中。) I have tried using array.sort and also by parsing subCode in integer but it has returned me different number which I didn't understand.(我已经尝试使用array.sort并通过解析subCode整数,但它已经回到了我不同的数字,我不明白。)   ask by Rishikesh Dehariya translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could subtract the the code properties inside the compareFunction.(您可以减去compareFunction中的代码属性。)

If both a and b have the same code property, then the ||(如果ab都具有相同的code属性,则||) operator will subtract the subCode property.(运算符将减去subCode属性。) The - operator will coerce the strings to numbers and it will return a numeric value.(-运算符会将字符串强制转换为数字,并将返回数字值。) const input=[{id:1,name:"ABP",code:1460,subCode:"0010"},{id:2,name:"GKY",code:1460,subCode:"0030"},{id:3,name:"CPT",code:1410,subCode:"0070"},{id:4,name:"KLB",code:1470,subCode:"0050"},{id:5,name:"POL",code:1430,subCode:"0050"},{id:6,name:"FVB",code:1410,subCode:"0050"},]; input.sort((a, b) => a.code - b.code || a.subCode - b.subCode) console.log(input)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...