步骤1.我需要根据索引合并3个数组。
步骤2.如果第一个数组中的两个项目匹配,我想合并它们的索引。
输入:
datesArray = ["2017-04-20", "2017-04-27", "2017-04-20"]
timesArray = ["13:00", "18:00", "14:00"]
pricesArray = ["40", "60", "50"]
输出:
[
{
"date": "2017-04-20",
"times": [
"13:00",
"14:00"
],
"prices": [
"$40.00",
"$50.00"
]
},
{
"date": "2017-04-27",
"times": [
"13:00"
],
"prices": [
"$30.00"
]
}
]
感谢您的帮助。
答案 0 :(得分:0)
您可以使用key-value
对对象进行分组,然后将其转换为数组。
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)
答案 1 :(得分:0)
您可以使用forEach()
循环执行此操作,并将一个空对象作为thisArg
参数传递,您可以使用该参数按日期对元素进行分组。
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);
&#13;