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

我有一个称为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 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,任何帮助都会对我有帮助


慕仙森
浏览 119回答 3
3回答

湖上湖

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

FFIVE

您可以创建->的Map,然后在数组上创建Array#map,检查日期是否存在于地图中。daterecordsCountmainDateArrayconst 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 dateconst recordsCount = [20, 30, 10]; // data for the above dates Array from responseconst 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);

肥皂起泡泡

你可以试试这个mainDateArray = [&nbsp; "05-May-19",&nbsp; "06-May-19",&nbsp; "07-May-19",&nbsp; "08-May-19",&nbsp; "09-May-19",&nbsp; "10-May-19",&nbsp; "11-May-19"];dates = ["06-May-19", "08-May-19", "10-May-19"]; // response daterecordsCount = [20, 30, 10];op = [];for (let i = 0; i < dates.length; i++) {&nbsp; for (let j = 0; j < mainDateArray.length; j++) {&nbsp; &nbsp; if (dates[i] === mainDateArray[j]) {&nbsp; &nbsp; &nbsp; op[j] = recordsCount[i];&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; if (!op[j]) op[j] = 0;&nbsp; &nbsp; }&nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript