为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕仙森 2021-05-04 17:27:52
我有一个称为mainDateArray的本地日期数组,我曾经调用过APi Calls进行响应,从响应中我得到了两个分别称为“ Dates”和“ RecordCount”的数组。此日期和记录计数具有相同的长度,并且recordCount数组包含与服务器中“日期”相对应的值。稍后,如果日期数组值与mainDateArray不匹配,我需要基于这两个“ mainDateArray”和“ recordCount”绘制图形,我需要在“ 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 daterecordsCount = [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,任何帮助都会对我有帮助
查看完整描述

3 回答

?
湖上湖

TA贡献2003条经验 获得超2个赞

使用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)


查看完整回答
反对 回复 2021-05-27
?
FFIVE

TA贡献1797条经验 获得超6个赞

您可以创建->的Map,然后在数组上创建Array#map,检查日期是否存在于地图中。daterecordsCountmainDateArray

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);


查看完整回答
反对 回复 2021-05-27
?
肥皂起泡泡

TA贡献1829条经验 获得超6个赞

你可以试试这个


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;

    }

  }

}


查看完整回答
反对 回复 2021-05-27
  • 3 回答
  • 0 关注
  • 118 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信