js & sort object keys All In One
js & sort object keys All In One
const months = ['3', '2', '1'];
console.log(months);
months.sort();
console.log(months);
/*
Array ["3", "2", "1"]
Array ["1", "2", "3"]
*/
"use strict";
/**
*
* @author xgqfrms
* @license MIT
* @copyright xgqfrms
* @created 2022-02-24
*
* @description js & sort object keys All In One
* @augments
* @example
* @link https://www.cnblogs.com/xgqfrms/p/15931874.html
*
*/
const log = console.log;
const obj = {
a: 3,
b: 1,
c: 2,
};
// Object.entries(obj)
[
[
"a",
3
],
[
"b",
1
],
[
"c",
2
]
];
const arr = Object.entries(obj)
for (const [k, v] of arr) {
console.log('k, v =', k, v);
}
// desc
arr.sort((a, b) => a[1] - b[1] > 0 ? 1 : -1);
// asc
arr.sort((a, b) => a[1] - b[1] > 0 ? -1 : 1);
// sort object keys
const sortKeys = arr.sort((a, b) => a[1] - b[1] > 0 ? -1 : 1).map(obj => obj[0]);
// ['a', 'c', 'b']
log('sortKeys', sortKeys);
demo
refs
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
https://en.wikipedia.org/wiki/In-place_algorithm
©xgqfrms 2012-2020
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/15931874.html
未经授权禁止转载,违者必究!