简体   繁体   English

Javascript映射数组的每个第n个元素

[英]Javascript map every nth element of array

I just started to learn Javascript by my own and faced quite complex task.我刚开始自学 Javascript 并面临着相当复杂的任务。

I have array where are 18 labels and another 1d array where are all of the values.我有一个数组,其中包含 18 个标签,另一个一维数组包含所有值。 The label index place match every nth element in array.标签索引位置匹配数组中的每个第 n 个元素。

Eg if label index is 0 so then the first element and 19th element belongs to label 1 and 2th and 20th element belongs to label in index 2 .例如,如果标签索引为 0,那么第一个元素和第 19 个元素属于标签 1,第 2 个和第 20 个元素属于索引 2 中的标签。

I wrote this script that create an Object and append the values from correct index, but is there better ways to map values between two arrays?我写了这个脚本来创建一个对象并从正确的索引附加值,但是有没有更好的方法来映射两个数组之间的值?

var labelArrLenght = 18;

var i = 0, sampleArr = [];
while (i < 6642) {
  sampleArr.push(i);
  i++;
};

var i = 0, myObj = {};
while (i < labelArrLenght) {
  myObj[i] = {label:`dummyLabel${i}`, data:[]};
  i++
};

var step1 = sampleArr.length / labelArrLenght;
var stepCounter = 0;

for (var i = 0; i < step1; i++) {
  for (var b = 0; b < labelArrLenght; b++) {
    myObj[b]['data'].push(sampleArr[stepCounter]);
    stepCounter++;
  };
};

You could take a single loop approach and get the index with the remainder operator % .您可以采用单循环方法并使用余数运算符%获取索引。

 var labelArrLenght = 18, sampleArr = [], myObj = {}; for (let i = 0; i < 90; i++) sampleArr.push(i); for (let i = 0; i < labelArrLenght ; i++) myObj[i] = { label: `dummyLabel${i}`, data: [] }; for (var i = 0; i < sampleArr.length; i++) myObj[i % labelArrLenght].data.push(sampleArr[i]); console.log(myObj);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM