【问题标题】:concat array of array after each 4 index每 4 个索引后的数组的 concat 数组
【发布时间】:2021-04-10 10:21:40
【问题描述】:

我有这种格式的数据

[["hi, hello, "bye"],["hi, hello, "bye"],["hi, hello, "bye"],["hi, hello, "bye"],["hi, hello, "bye"],["hi, hello, "bye"],["hi, hello, "bye"],["hi, hello, "bye"]] 

我想将 4 个索引连接到新数组,所以新数组将是

[["hi, hello, "bye","hi, hello, "bye","hi, hello, "bye","hi, hello, "bye"],["hi, hello, "bye","hi, hello, "bye","hi, hello, "bye","hi, hello, "bye"]]

我正在尝试使用此代码,但不知道该怎么做

const table = document.querySelectorAll('table[class=ProductInventory]')[1];
    const data = [];
    const finalData =[]

    for (var i = 1; i < table.rows.length; i++) {
        var tableRow = table.rows[i];
        var rowData = [];
        for (var j = 0; j < tableRow.cells.length; j++) {
            rowData.push(tableRow.cells[j].innerText);
        }
        data.push(rowData);
    } 
   let counter = 1
    for (var a = 0; a <= data.length / 4; a++) {
            const obj = []
            counter++
            if(counter == 4){
                obj.concat(data[a-3], data[a - 2], data[a - 1]);
                counter = 0
            }
            
            finalData.push(obj)
        }

【问题讨论】:

标签: javascript arrays json foreach transformation


【解决方案1】:

您可以将Array.fromArray#slice 一起使用。

const arr = [["hi", "hello", "bye"],["hi", "hello", "bye"],["hi", "hello", "bye"],["hi", 'hello', "bye"],["hi", 'hello', "bye"],["hi", 'hello', "bye"],["hi", 'hello', "bye"],["hi", 'hello', "bye"]];
const size = 4;
const res = Array.from({length: Math.ceil(arr.length / size)}, 
    (_,i)=>arr.slice(i * size, (i + 1) * size).flat());
console.log(res);

【讨论】:

  • @HimanshuTak 如果解决了您的问题,您介意accepting我的回答吗?
【解决方案2】:

你可以使用 JavaScript Array reduce() 方法

const data = [["hi", "hello", "bye"],["hi", "hello", "bye"],["hi", "hello", "bye"],["hi", 'hello', "bye"],["hi", 'hello', "bye"],["hi", 'hello', "bye"],["hi", 'hello', "bye"],["hi", 'hello', "bye"]];
const finalData = data.reduce((finalVal, currenctVal, currenctIndex) => {
    let index = Math.floor(currenctIndex / 4);
    if(!finalVal[index]) {
       finalVal[index] = [];
    }
    finalVal[index] = finalVal[index].concat(currenctVal);
    return finalVal;
     
},[]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-27
    • 1970-01-01
    相关资源
    最近更新 更多