如何有条件地基于多个键对数组进行分组?

时间:2019-02-11 11:01:03

标签: javascript

我有一个简单的问题,有条件地分组。

const aInput = [
{"date":"2018/9/10", "code":"A"},
{"date":"2018/9/10", "code":"B"},
{"date":"2018/9/11", "code":"B"},
{"date":"2018/9/11", "code":"B"}];

我想按日期对数组进行分组,但如果一天中都存在A和B,那么只有B停留

const aInput = [
{"date":"2018/9/10", "code":"A"},
{"date":"2018/9/10", "code":"B"},
{"date":"2018/9/11", "code":"B"},
{"date":"2018/9/11", "code":"B"}];


// I want to group the array above by day & code BUT if there is both A & B then only B stays


const aOutput = [
{"date":"2018/9/10", "code":"B"},
{"date":"2018/9/11", "code":"B"}]

2 个答案:

答案 0 :(得分:2)

您可以使用reduce做这样的事情:

使用每个date作为键创建一个累加器。如果累加器的上下文中没有当前日期,或者当前对象具有首选代码,则将该对象添加为值。

(添加了一个额外的A代码对象进行演示)

const aInput = [
	{"date":"2018/9/10", "code":"A"},
	{"date":"2018/9/10", "code":"B"},
	{"date":"2018/9/11", "code":"B"},
	{"date":"2018/9/11", "code":"B"},
	{"date":"2018/9/12", "code":"A"}]

const preferredCode = "B";

const merged = aInput.reduce((r,{date, code}) =>{
  if(!r[date] || code === preferredCode)
      r[date] = {date, code};

  return r;
},{})

const final = Object.values(merged)

console.log(final)

上面的代码假设只有2个code。如果您有2个以上的code,并且希望每天获取所有唯一代码(除非有B,则可以使用reduce和{{1})进行以下操作}

some

答案 1 :(得分:0)

您可以使用.reduce

在此数组中按代码分组

const aInput = [
{"date":"2018/9/10", "code":"A"},
{"date":"2018/9/10", "code":"B"},
{"date":"2018/9/11", "code":"B"},
{"date":"2018/9/11", "code":"B"}];

const result = aInput.reduce((r, a) => {
  r[a.code] = [...r[a.code] || [], a];
  return r;
}, {});

console.log(result)