简体   繁体   中英

Modify repeated values in javaScript

There is an array of JavaScript:

let arr=[
[220,A,12],
[560,B,5],
[300,A,0],
[300,H,3], 
[300,K,T],
[450,P,9],
[500,E,6],
[500,M,8]
];

The first element of sub-arrays have some repeated values,
I want to find them and modify the repeated values, as follow:

[300,A,0],  ===>  remain unchanged
[300,H,3],  ===>  [320,H,3],  //First element add 20
[300,K,T],  ===>  [340,K,T],  //First element add 20 again

[500,E,6],  ===>  remain unchanged
[500,M,8]   ===>  [520,M,8] //First element add 20

That is, the first element adds 20 in proper order if repeated.
Other elements don't need to be considered.
How to do it in javaScript?

One option is to use reduce . I pass an object as the initial value to reduce :

{
    last: null,  // The previous number encountered
    offset: 20,  // The amount to add on repeat
    data: []     // The new array
}

Then, use this to build the new array:

 let arr=[ [220,'A',12], [560,'B',5], [300,'A',0], [300,'H',3], [300,'K','T'], [450,'P',9], [500,'E',6], [500,'M',8] ]; arr = arr.reduce((prev, cur) => { // Is this a repeat? if (prev.last == cur[0]) { cur[0] += prev.offset; prev.offset += 20; } // Not a repeat. Reset. else { prev.last = cur[0]; prev.offset = 20; } prev.data.push(cur); return prev; }, {last: null, offset: 20, data: []}).data; console.log(arr);

using map key:value, where key is number and value is its occurrence so far

 let arr = [ [220, 12], [560, 5], [300, 0], [300, 3], [300, 0], [450, 9], [500, 6], [500, 8] ]; m = {} for (let i = 0; i < arr.length; ++i) { const x = arr[i][0] if (m[x] > 0){ arr[i][0] += (m[x]) *20 m[x]++ } else m[x] = 1 } console.log(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