简体   繁体   中英

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] . You can't use an array to index an 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. Whenever I check a new array, I store it in checkedArr and will check against it to prevent duplicate records.

 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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