如何选择数组中的数字

时间:2019-01-11 16:09:08

标签: javascript

我正在尝试选择三个一组中的每个第二个元素。例如

[4, 5, 3, 2, 3, 1, 4, 5, 3]

结果:5、3、5

我该如何实现?

4 个答案:

答案 0 :(得分:3)

您可以使用Array.prototype.filtermodulo operation

const result = [4, 5, 3, 2, 3, 1, 4, 5, 3].filter((item, i) => (i+2) % 3 === 0);

console.log(result)

答案 1 :(得分:0)

您必须将数组拆分为块,然后获取每个块的第二个元素

/**
 * Returns an array with arrays of the given size.
 *
 * @param myArray {Array} array to split
 * @param chunk_size {Integer} Size of every group
 */
function chunkArray(myArray, chunk_size){
    var index = 0;
    var arrayLength = myArray.length;
    var tempArray = [];
    
    for (index = 0; index < arrayLength; index += chunk_size) {
        myChunk = myArray.slice(index, index+chunk_size);
        // Do something if you want with the group
        tempArray.push(myChunk);
    }

    return tempArray;
}
// Split in group of 3 items



function getResult () {
  // Outputs : [ [1,2,3] , [4,5,6] ,[7,8] ]
  var chunked = chunkArray([1,2,3,4,5,6,7,8], 3);
  var result = [];
  for(var i = 0; i < chunked.length; i++){
    result.push(chunked[i][1]);
  }
  return result;
  
}
console.log(getResult());

分组参考:https://ourcodeworld.com/articles/read/278/how-to-split-an-array-into-chunks-of-the-same-size-easily-in-javascript

答案 2 :(得分:0)

var arr = [4, 5, 3, 2, 3, 1, 4, 5, 3],
    filtered = arr.filter((val,idx) => idx % 3 == 1);

答案 3 :(得分:0)

//this function splits arrays into groups of n
function chunk(arr, limit) {
  var chunks = [];
  for (var i=0,len=arr.length; i<len; i+=limit)
    chunks.push(arr.slice(i,i+limit));
  return chunks;
}


var arr =  [4, 5, 3, 2, 3, 1, 4, 5, 3]

//split array in groups
var chunked = chunk(arr, 3);

//for each array in chunked array, do something with second item
chunked.forEach(function(i) {
    console.log(i[1]);
});

//You can also do:

chunked[2][1]