# Create an object of arrays with their corresponding winners

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] = [];
}
}
```

Mohammad Usman
answered question

CertainPerformance
commented

Why is `carl`

included in the `Ali`

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

### 1 Answer

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; }`

Mohammad Usman
posted this

## Have an answer?

JD

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