[英]How do i multiple sort an array per column for all lines ? (JavaScript)
[英]How do i split an array per column for all columns? (JavaScript)
您好,JavaScript同行,
我有一個從csv文件中的數據創建的數組,如下所示:
在這種情況下,每個數組索引(例如array [0])都是標頭,其中有87個標頭。 該數組中的所有其他數組都是行。
我需要獲取該數據並在各列之間進行拆分
以下代碼僅用於第一列:
var specialCounter = 0;
for(var j = 1; j<vm.lines.length; j++){
vm.columns.push(vm.lines[j][0]);
if(specialCounter >= vm.lines[j][0].length)
specialCounter = 0;
else
specialCounter++;
}
vm.columnData.columnData= vm.columns;
console.log(vm.columnData);
這是它吐出的數組。
我如何對此數組中的所有列執行此操作?
可能具有類似vm.dataPerColumn = [{column1: [...], column2: [...], etc...]
減少數組, forEach子數組檢查鍵是否存在,如果不存在,請在結果對象( r
)上創建鍵。 將當前項目按到鍵:
var arr = [['h1', 1, 2, 3], ['h2', 4 , 5 , 6], ['h3', 7, 8, 9]]; var result = arr.reduce(function(r, a) { a.forEach(function(s, i) { var key = i === 0 ? 'headers' : 'column' + i; r[key] || (r[key] = []); // if key not found on result object, add the key with empty array as the value r[key].push(s); }); return r; }, {}); console.log(result);
通過閱讀說明並查看圖片,標題似乎在array[0]
const vm = {};
vm.lines = [["$", "house", "car"],[5, 10, 15],[25,35,45]];
const headers = vm.lines[0];
const data = vm.lines.slice(1);
const columns = data.reduce((newColumns, row) => {
for(let i=0;i<row.length;i++){
if(newColumns.length-1 < i){ //first column;
newColumns.push([]);
}
newColumns[i].push(row[i]);
}
return newColumns;
}, []);
const columnsWithHeaders = headers.map((header, index) => ({[header]:columns[index]}));
console.log(columnsWithHeaders);
您請求了column1,column2等,但是當您已經有一個數組時,這實際上沒有任何意義,因此我將標題名稱與相應的列放在一起,然后可以直接引用它
我所做的是將標題和數據分開。 因此您不必擔心第一行,
然后,我將行轉換為列,然后,您可以遍歷標題並將列數組添加到每個標題中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.