简体   繁体   English

在javascript中按值排序

[英]sorting by value in maps in javascript

I have an object with many-to-one mapping:我有一个多对一映射的对象:

{
  'a' : 'one',
  'b' : 'two',
  'c' : 'one',
  'd' : 'two'
}

Now I want to make the following object from this:现在我想从中制作以下对象:

{
  'one' : ['a' , 'c'],
  'two' : ['b' , 'd']
}

What is the most efficient way to do this in javascript (we can also use underscore libraries if it helps) Note: The above objects are just a shorter version of the actual problem.在 javascript 中执行此操作的最有效方法是什么(如果有帮助,我们也可以使用下划线库) 注意:上述对象只是实际问题的较短版本。

var data = {
  'a' : 'one',
  'b' : 'two',
  'c' : 'one',
  'd' : 'two'
}

var result = {};

for(var key in data) {
    var val = data[key];
    if(!result[val]) result[val] = [];

    result[val].push(key);
}

console.log(result);

You can do this with Object.keys() and reduce你可以用Object.keys()做到这一点并reduce

 var data = {'a': 'one','b': 'two','c': 'one','d': 'two'} var result = Object.keys(data).reduce((res, e) => { res[data[e]] = (res[data[e]] || []).concat(e); return res; }, {}); console.log(result)

You could also use forEach and add to created object您还可以使用forEach并添加到创建的对象

 var data = {'a': 'one','b': 'two','c': 'one','d': 'two'}, r = {} Object.keys(data).forEach(e => {r[data[e]] = (r[data[e]] || []).concat(e)}); console.log(r)

Well, here's my approach.嗯,这是我的方法。 Not as advanced as Nenad's though.虽然不如 Nenad 先进。

var obj = {
  'a' : 'one',
  'b' : 'two',
  'c' : 'one',
  'd' : 'two'
};

var result = {};

for (var i in obj) {
  if (obj[i] in result) {
    result[obj[i]].push(i);
  } else {
    result[obj[i]] = [i];
  }
}

console.log(result);

a single liner单班轮

 var map = { 'a' : 'one', 'b' : 'two', 'c' : 'one', 'd' : 'two' }, reduced = Object.keys(map).reduce((p,c) => {!!p[map[c]] ? p[map[c]].push(c) : p[map[c]] = [c]; return p},{}) document.write("<pre>" + JSON.stringify(reduced) + "</pre>");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM