Create an object of arrays with their corresponding winners

1480 views javascript
-1

say I have an array:

let array = [
  { win: "Ali", loser: "Jake"},
  { win: "carl", loser: "Dean"},
  { win: "Eli", loser: "Jake"},
  { win: "Eli", loser: "carl"},
  { win: "Ali", loser: "carl"},
  { win: "carl", loser: "Dean"},
  { win: "Dean", loser: "Eli"}
];

output should be:

{
  'Ali': ['Jake', 'carl'],
  'Jake':   [],
  'carl': ['Dean'],
  'Dean':  ['eli'],
  'eli': ['Jake', 'carl'],
}

So my first step is to create an empty array of all the winners inside of an object. Then push each element of winner with their corresponding loser. But I'm a bit lost on the approach. What I have:

function winner(array) {
  let newObj = {};

  for (let obj of array) {
    newObj[obj.winner] = [];
  }
}

answered question

Can you explain more how the input gets turned into the output? The process isn't very clear

@CertainPerformance just made the edit basically need to output winners and their losers

Could you clarify exactly what your code is supposed to do? How did you determine the output from the array? It isn't clear.

Why is carl included in the Ali array in the output? (Ali did not win over carl in the input)

Is Ali supposed to be eli?

@CertainPerformance you're right. I fixed the output.

@inavda yes. fixed it.

1 Answer

7

You can use .reduce() to get the desired output:

let array = [{ win: "Ali", loser: "Jake"}, { win: "carl", loser: "Dean"}, { win: "Eli", loser: "Jake"}, { win: "Eli", loser: "carl"}, { win: "Ali", loser: "carl"}, { win: "carl", loser: "Dean"}, { win: "Dean", loser: "Eli"}];

let result = array.reduce((r, c) => {
  r[c.win] = r[c.win] || [];
  if(!r[c.win].includes(c.loser)) {
    r[c.win].push(c.loser);
  }
  return r;
}, {});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

posted this

Have an answer?

JD

Please login first before posting an answer.