如何根据索引位置映射数组

时间:2019-05-11 04:46:22

标签: javascript arrays

我有一个称为mainDateArray的本地日期数组,我曾经调用过APi Calls进行响应,从响应中我得到了两个分别称为“ Dates”和“ RecordCount”的数组。此日期和记录计数具有相同的长度,并且recordCount数组包含与服务器中“日期”相对应的值。

后来我需要基于这两个“ mainDateArray”和“ recordCount”绘制图形 如果日期数组值与mainDateArray不匹配,则需要在“ recordsCount”数组上附加或将0推入

更清楚

mainDateArray = ["05-May-19","06-May-19","07-May-19","08-May-19","09-May-19","10-May-19","11-May-19"];
dates = ["06-May-19","08-May-19","10-May-19"]; // response date
recordsCount = [20,30,10];  // data for the above dates Array from response

我的预期输出

op = [0,20,0,30,0,10,0];
example:=> ["05-May-19"=0,"06-May-19"=20,"07-May-19"=0,"08-May-19"=30,"09-May-19"=0,"10-May-19"=10,"11-May-19"=10]

即,当我的响应日期不包括maindateArray时,我需要在recordCount数据中附加0,任何帮助都会对我有帮助

5 个答案:

答案 0 :(得分:1)

使用Array​​.map()Array​​.indexOf()

var mainDateArray = ["05-May-19", "06-May-19", "07-May-19", "08-May-19", "09-May-19", "10-May-19", "11-May-19"]
var dates = ["06-May-19", "08-May-19", "10-May-19"]
var recordsCount = [20, 30, 10]

var result = mainDateArray.map((v, i) => recordsCount[dates.indexOf(v)] || 0)

console.log(result)

答案 1 :(得分:1)

您可以在date数组中创建recordsCount-> mainDateArray中的Map,然后在const mainDateArray = [ "05-May-19", "06-May-19", "07-May-19", "08-May-19", "09-May-19", "10-May-19", "11-May-19" ]; const dates = ["06-May-19", "08-May-19", "10-May-19"]; // response date const recordsCount = [20, 30, 10]; // data for the above dates Array from response const datesMap = new Map(dates.map((date, idx) => [date, recordsCount[idx]])); const op = mainDateArray.map(date => datesMap.has(date) ? datesMap.get(date) : 0 ); console.log(op);数组上创建Array#map,检查地图中是否存在日期或不是。

class="menu__overlay--bottom"

答案 2 :(得分:0)

IMO最简单的方法是使用一个对象来跟踪计数。

// create object for key (i.e. date) based lookup
var counts = {};
for(var i in mainDateArray){
    var date = mainDateArray[i];
    counts[date] = 0;
}

// update counts
for(var i in dates){
    var date = dates[i];
    counts[date] += recordsCount[i];
}

// output
var op = [];
for(var i in mainDateArray){
    var date = mainDateArray[i];
    op.push(counts[date]);
}

答案 3 :(得分:0)

您可以尝试

mainDateArray = [
  "05-May-19",
  "06-May-19",
  "07-May-19",
  "08-May-19",
  "09-May-19",
  "10-May-19",
  "11-May-19"
];
dates = ["06-May-19", "08-May-19", "10-May-19"]; // response date
recordsCount = [20, 30, 10];
op = [];
for (let i = 0; i < dates.length; i++) {
  for (let j = 0; j < mainDateArray.length; j++) {
    if (dates[i] === mainDateArray[j]) {
      op[j] = recordsCount[i];
    } else {
      if (!op[j]) op[j] = 0;
    }
  }
}

答案 4 :(得分:0)

input

output = [0,06-May-19,0,08-May-19,0,10-May-19,0]