TechDev
TechDev

Reputation: 433

Not printing the array correctly when reduce

i have 1 javascript array. i wanted to merge this array based on the dates and get each of the price and put in the field. However the price im only getting is 1. the other price with the same date is not printing. Can anyone help me why ? Thank you

Here is the code:

Javascript:

var data = [
   {
      "date":"2010-01-01",
      "name":"a"
   },
   {
      "date":"2010-02-01",
      "name":"b"
   },
   {
      "date":"2010-03-01",
      "name":"c"
   },
   {
      "date":"2010-01-01",
      "name":"aa"
   },
   
]

var result1 = data.reduce((p, c) => 
  (p[c.date] = Object.assign({},{name: null}, p[c.date], c)) && p
  , {});

var final = Object.keys(result1).map(x=>result1[x])

console.log(final)

You can access the code here:

https://jsfiddle.net/q0wn2vuo/

I want the output like this:

[{ date: "2010-01-01", name: 'a,aa', }, { date: "2010-02-01", name: 'b', }, { date: "2010-03-01", price: 'c', }]

Upvotes: 0

Views: 60

Answers (2)

albert
albert

Reputation: 474

try:

var data = [
   {
      "date":"2010-01-01",
      "name":"a"
   },
   {
      "date":"2010-02-01",
      "name":"b"
   },
   {
      "date":"2010-03-01",
      "name":"c"
   },
   {
      "date":"2010-01-01",
      "name":"aa"
   },  
]


var result1 = data.reduce((accum, curr) => {
  if (!accum[curr.date]) {
    return {...accum, [curr.date]: [curr.name] }
  }
  return {...accum, [curr.date]: [...accum[curr.date], curr.name] }
}, {})

var final = Object.keys(result1).map(date => ({
  date: date,
  name: result1[date].join(',')
}))

console.log(final)

Upvotes: 0

JustRaman
JustRaman

Reputation: 1161

Here you go.

var data = [
   {
  "date":"2010-01-01",
  "name":"a"
   },
   {
  "date":"2010-02-01",
  "name":"b"
   },
   {
  "date":"2010-03-01",
  "name":"c"
   },
   {
  "date":"2010-01-01",
  "name":"aa"
   },
   
]

const resultSet = {};

 for (let i = 0, _len = data.length; i < _len; i++ ) {
       if(resultSet[data[i].date]){
        resultSet[data[i].date] += ","+data[i].name
       }
       else{
        resultSet[data[i].date] = data[i].name
       }
       
    }

const resultArr = Object.entries(resultSet).map(([key,value])=>{
 return { date: key, name: value }
})
console.log(resultArr)

Upvotes: 1

Related Questions