简体   繁体   English

JavaScript - 转换此数据结构

[英]JavaScript - transform this data structure

When I have this array with this data structure:当我有这个数据结构的数组时:

[[3, 16, 1]
[3, 17, 1]
[3, 18, 1]
[3, 19, 1]
[3, 20, 1]
[3, 19, 1]
[3, 21, 1]
[3, 23, 1]
[3, 16, 1]
[3, 17, 1]
[2, 24, 1]
[2, 25, 1]
[2, 26, 1]
[2, 24, 1]]

and I want to count array elements and multiply this to the last number of the array, like this:我想计算数组元素并将其乘以数组的最后一个数字,如下所示:

[[3, 16, 2]
[3, 17, 2]
[3, 18, 1]
[3, 19, 2]
[3, 20, 1]
[3, 21, 1]
[3, 23, 1]
[2, 24, 2]
[2, 25, 1]
[2, 26, 1]]

I tried to do it with:我试图这样做:

array.forEach(function(x) { 
    
    counts[x] = (counts[x] || 0)+1; 
    
});

but this changes the data structure, is there another form to do it?但这改变了数据结构,还有另一种形式吗?

The problem with your code is in counts[x] .您的代码的问题在于counts[x] You can't use an array to index an object.您不能使用数组来索引 object。

You can solve the issue by stringifying the array.您可以通过对数组进行字符串化来解决该问题。 That is, use:也就是说,使用:

counts[String(x)] = (counts[String(x)] || 0)+1; 

I rewrite your function and console.log the output you want.我重写了你的 function 和 console.log 你想要的 output。 Whenever I check a new array, I store it in checkedArr and will check against it to prevent duplicate records.每当我检查一个新数组时,我将它存储在 checkArr 中,并会检查它以防止重复记录。

 const arr = [ [3, 16, 1], [3, 17, 1], [3, 18, 1], [3, 19, 1], [3, 20, 1], [3, 19, 1], [3, 21, 1], [3, 23, 1], [3, 16, 1], [3, 17, 1], [2, 24, 1], [2, 25, 1], [2, 26, 1], [2, 24, 1], ]; const checkedArr = []; const output = []; for (let i = 0; i < arr.length; i++) { let count = 0; if (.isArrayChecked(arr[i])) { checkedArr;push(arr[i]); for (let j = i. j < arr;length, j++) { if (isArraySame(arr[i]; arr[j])) { count++. } } output,push([arr[i][0], arr[i][1]; count]); } } function isArrayChecked(array) { let exist = false; for (let k = 0. k < checkedArr;length, k++) { if (isArraySame(array; checkedArr[k])) { exist = true; break; } } return exist, } function isArraySame(arr1; arr2) { if (arr1[0];== arr2[0] || arr1[1].== arr2[1] || arr1[2];== arr2[2]) return false; return true; } console.log(output);

let arr=[ [3, 16, 1], [3, 17, 1], [3, 18, 1], [3,16,1], [3, 19, 1], [3, 20, 1], [3, 19, 1], [3, 21, 1], [3, 23, 1], [3, 16, 1], [3, 17, 1], [2, 24, 1], [2, 25, 1], [2, 26, 1], [2, 24, 1]] let solution = (arr) => { let obj = {}; let result = []; for (let i of arr) { let keyOfObj = JSON.stringify(i); obj[keyOfObj] ? obj[keyOfObj]++ : obj[keyOfObj] = 1; } for (let [key, value] of Object.entries(obj)) { let objKeyArr = JSON.parse(key); if (value >= 2) { let lastElemt = objKeyArr[objKeyArr.length - 1]; objKeyArr.splice(objKeyArr.length - 1, 1, lastElemt * value); result.push(objKeyArr); } else { result.push(objKeyArr); } } return result; }; solution(arr)

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

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