1

Step 1. I need to merge 3 arrays based on the indexes.

Step 2. If two items in the first array match, I want to merge their indices.

Input:

datesArray  = ["2017-04-20", "2017-04-27", "2017-04-20"]
timesArray  = ["13:00", "18:00", "14:00"]
pricesArray = ["40", "60", "50"]

Output:

[
  {
    "date": "2017-04-20",
    "times": [
      "13:00",
      "14:00"
    ],
    "prices": [
      "$40.00",
      "$50.00"
    ]
  },
  {
    "date": "2017-04-27",
    "times": [
      "13:00"
    ],
    "prices": [
      "$30.00"
    ]
  }
]

Thanks for your help.

anon
  • 154
  • 9
  • 1
    You should just type out the expected result. That will make it easier to read, and make it more likely someone will help you. You should also show an attempt you've written, to at least show us that you've tried something. – Andrew Shepherd Apr 18 '17 at 04:50
  • 1
    How do you get "repeated indexes" in an array? – RobG Apr 18 '17 at 04:51
  • @RobG I think he mean't repeated values – aaronw Apr 18 '17 at 04:58
  • @RobG, @AndrewShepherd it comes from a web service. I'm working in a dynamic calendar so I need dates, times and price separated but merge in the way explained above to finish other tasks. I'm currently away of the computer :( Web service portion, as you may see the arrays are related in the index position. `price_date: [ "2017-04-20 13:00", "2017-04-27 18:00", "2017-04-20 14:00" ], price: [ "40", "60", "50" ]` – Teddy Jimenez Apr 18 '17 at 05:11

2 Answers2

0

You can use key-value pairs to group objects and then convert it to an array.

var datesArray  = ["2017-04-20", "2017-04-27", "2017-04-20"]
var timesArray  = ["13:00", "18:00", "14:00"]
var pricesArray = ["40", "60", "50"]

var result = {}, mergedArray = []

for(var i=0;i<datesArray.length;i++){
  var e = datesArray[i]
  if(!result[e]){
      result[e]={ date: e, times: [], prices: [] }
  }
  result[e].times.push(timesArray[i])
  result[e].prices.push('$' + pricesArray[i] + '.00')
}

for (var key in result){
    if (result.hasOwnProperty(key)) {
         mergedArray.push(result[key]);
    }
}

console.log(mergedArray)
Gaurav Chaudhary
  • 1,491
  • 13
  • 28
0

You can do this with forEach() loop and pass one empty object as thisArg parameter that you can use to group elements by date.

var datesArray  = ["2017-04-20", "2017-04-27", "2017-04-20"]
var timesArray  = ["13:00", "18:00", "14:00"]
var pricesArray = ["40", "60", "50"]

var result = [];
datesArray.forEach(function(e, i) {
  if(!this[e]) {
    this[e] = {date: e, times:[], prices: []}
    result.push(this[e]);
  }
  this[e].times.push(timesArray[i]);
  this[e].prices.push('$' + pricesArray[i] + '.00');
});

console.log(result);
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176