Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

142
Views
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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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);

about 4 years ago · Juan Pablo Isaza Report

0

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)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!