【问题标题】:Merge arrays into new array based on indexes and repeated indexes [duplicate]根据索引和重复索引将数组合并到新数组中[重复]
【发布时间】:2017-09-13 19:03:56
【问题描述】:

步骤 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"
    ]
  }
]

感谢您的帮助。

【问题讨论】:

  • 您应该只输入预期的结果。这将使阅读更容易,并且更有可能有人会帮助您。您还应该展示您编写的尝试,至少向我们展示您已经尝试过一些东西。
  • 如何在数组中获得“重复索引”?
  • @RobG 我认为他的意思不是重复值
  • @RobG, @AndrewShepherd 它来自网络服务。我正在使用动态日历,因此我需要将日期、时间和价格分开,但以上述方式合并以完成其他任务。我目前不在计算机中 :( Web 服务部分,您可能会看到数组与索引位置相关。price_date: [ "2017-04-20 13:00", "2017-04-27 18:00", "2017-04-20 14:00" ], price: [ "40", "60", "50" ]

标签: javascript arrays json merge


【解决方案1】:

您可以使用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)

【讨论】:

    【解决方案2】:

    您可以使用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);

    【讨论】:

      猜你喜欢
      • 2021-12-22
      • 2012-12-21
      • 2010-10-28
      • 1970-01-01
      • 1970-01-01
      • 2012-05-18
      • 2017-08-03
      • 2011-11-25
      • 1970-01-01
      相关资源
      最近更新 更多