如果我有一个JavaScript对象,如:
var list = {
"you": 100,
"me": 75,
"foo": 116,
"bar": 15
};
是否有一种方法可以根据值对属性进行排序?最后得到
list = {
"bar": 15,
"me": 75,
"you": 100,
"foo": 116
};
如果我有一个JavaScript对象,如:
var list = {
"you": 100,
"me": 75,
"foo": 116,
"bar": 15
};
是否有一种方法可以根据值对属性进行排序?最后得到
list = {
"bar": 15,
"me": 75,
"you": 100,
"foo": 116
};
当前回答
我已经用自己的方式尝试过了
var maxSpeed = {
car: 300,
bike: 60,
motorbike: 200,
airplane: 1000,
helicopter: 400,
rocket: 8 * 60 * 60
};
var sorted = {}
Object.keys(maxSpeed).sort ((a,b) => maxSpeed[a] - maxSpeed[b]).map(item => sorted[item] = maxSpeed[item]);
console.log(sorted)
其他回答
输入是对象,输出是对象,使用lodash & js内置库,降序或升序选项,不改变输入对象
Eg输入输出
{
"a": 1,
"b": 4,
"c": 0,
"d": 2
}
{
"b": 4,
"d": 2,
"a": 1,
"c": 0
}
实现
const _ = require('lodash');
const o = { a: 1, b: 4, c: 0, d: 2 };
function sortByValue(object, descending = true) {
const { max, min } = Math;
const selector = descending ? max : min;
const objects = [];
const cloned = _.clone(object);
while (!_.isEmpty(cloned)) {
const selectedValue = selector(...Object.values(cloned));
const [key, value] = Object.entries(cloned).find(([, value]) => value === selectedValue);
objects.push({ [key]: value });
delete cloned[key];
}
return _.merge(...objects);
}
const o2 = sortByValue(o);
console.log(JSON.stringify(o2, null, 2));
打印稿
下面的函数根据值或值的属性对对象进行排序。如果你不使用TypeScript,你可以删除类型信息,将其转换为JavaScript。
/**
* Represents an associative array of a same type.
*/
interface Dictionary<T> {
[key: string]: T;
}
/**
* Sorts an object (dictionary) by value or property of value and returns
* the sorted result as a Map object to preserve the sort order.
*/
function sort<TValue>(
obj: Dictionary<TValue>,
valSelector: (val: TValue) => number | string,
) {
const sortedEntries = Object.entries(obj)
.sort((a, b) =>
valSelector(a[1]) > valSelector(b[1]) ? 1 :
valSelector(a[1]) < valSelector(b[1]) ? -1 : 0);
return new Map(sortedEntries);
}
使用
var list = {
"one": { height: 100, weight: 15 },
"two": { height: 75, weight: 12 },
"three": { height: 116, weight: 9 },
"four": { height: 15, weight: 10 },
};
var sortedMap = sort(list, val => val.height);
JavaScript对象中键的顺序是不保证的,所以我将排序并将结果返回为一个保留排序顺序的Map对象。
如果你想把它转换回Object,你可以这样做:
var sortedObj = {} as any;
sortedMap.forEach((v,k) => { sortedObj[k] = v });
找出每个元素的频率,并按频率/值进行排序。
Let response =["苹果","橘子","苹果","香蕉","橘子","香蕉","香蕉"]; 设frequency = {}; response.forEach(函数(项){ 频率[项目]=频率[项目]?频率[项]+ 1:1; }); console.log(频率); let intents = Object.entries(frequency) .sort((a, b) => b[1] - a[1]) . map(函数(x) { 返回x [0]; }); console.log(意图);
输出:
{ apple: 2, orange: 2, banana: 3 }
[ 'banana', 'apple', 'orange' ]
你的对象可以有任意数量的属性,如果你把对象放在数组中,你可以选择根据你想要的任何对象属性进行排序,数字或字符串。考虑这个数组:
var arrayOfObjects = [
{
name: 'Diana',
born: 1373925600000, // Mon, Jul 15 2013
num: 4,
sex: 'female'
},
{
name: 'Beyonce',
born: 1366832953000, // Wed, Apr 24 2013
num: 2,
sex: 'female'
},
{
name: 'Albert',
born: 1370288700000, // Mon, Jun 3 2013
num: 3,
sex: 'male'
},
{
name: 'Doris',
born: 1354412087000, // Sat, Dec 1 2012
num: 1,
sex: 'female'
}
];
按出生日期排序,最年长的先
// use slice() to copy the array and not just make a reference
var byDate = arrayOfObjects.slice(0);
byDate.sort(function(a,b) {
return a.born - b.born;
});
console.log('by date:');
console.log(byDate);
按名称排序
var byName = arrayOfObjects.slice(0);
byName.sort(function(a,b) {
var x = a.name.toLowerCase();
var y = b.name.toLowerCase();
return x < y ? -1 : x > y ? 1 : 0;
});
console.log('by name:');
console.log(byName);
http://jsfiddle.net/xsM5s/16/
按值排序对象属性
Const obj ={你:100,我:75,foo: 116, bar: 15}; const keysSorted = Object.keys(obj)。排序((a, b) => obj[a] - obj[b]); Const result = {}; keysSorted。forEach(key => {result[key] = obj[key];}); 文档。write('Result: ' + JSON.stringify(Result));
期望的输出:
{"bar":15,"me":75,"you":100,"foo":116}
引用:
按值排序对象属性 将数组转换为对象