0

I have a simple issue grouping conditionally.

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 by day & code BUT if there is both A & B for one day then only B stays

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"}]
adiga
  • 34,372
  • 9
  • 61
  • 83
Louis
  • 622
  • 2
  • 10
  • 26

2 Answers2

2

You could do something like this using reduce:

Create an accumulator with each date as key. If the accumulator doesn't have the current date in context or if the current object has the preferred code, then add the object as value.

(Added an additional A code object to demonstrate)

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)

The above code assumes that there are only 2 codes. If you have more than 2 codes and you want to get all the unique codes per day unless there is a B, then you can do the following using reduce and some

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"},
{"date":"2018/9/12", "code":"C"}]

const preferredCode = "B";

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

const final = [].concat.apply([],Object.values(merged))

console.log(final)
adiga
  • 34,372
  • 9
  • 61
  • 83
0

You can group by code in this array by using .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)
Khyati Sharma
  • 109
  • 1
  • 9