Aman Gupta
Aman Gupta

Reputation: 1874

How to update values of each object in the array of objects in Javascript?

I have an array having multiple objects:

[ {col:1} {col:1} {col:1} {col:3} {col:3} {col:9} {col:12} {col:13} ]

I want to update this array such that col having values 1 will remain same while the next value (here 3) should become 2 and then next value(here 9) should become 3 and so on..

O/P:

[ {col:1} {col:1} {col:1} {col:2} {col:2} {col:3} {col:4} {col:5} ]

Please help.

Upvotes: 1

Views: 118

Answers (4)

charlietfl
charlietfl

Reputation: 171679

Should do what is needed. Doesn't rely on any specific order in original array and assumes will always start at 1

var data=[ {col:1} ,{col:1} ,{col:1} ,{col:3} ,{col:3}, {col:9} ,{col:12} ,{col:13} ];

var uniqueValues = data.reduce(function(a,c){
   if(a.indexOf(c.col)===-1) {
      a.push(c.col);
   }  
   return a;
},[]).sort(function(a,b){
   return a-b;
}); // produces [1,3,9,12,13]

var res=data.map(function(item){
   // use index of current col value from unique values .. plus one
   item.col=uniqueValues.indexOf(item.col) + 1;
   return item;
});

document.getElementById('pre').innerHTML = JSON.stringify(res,null,4)
<pre id="pre">

Edit: if lowest col isn't 1 can still use uniqueValues.indexOf(item.col) + uniqueValues [0]

Upvotes: 1

mjr
mjr

Reputation: 807

Here is a fairly simple method:

var arr = [ {col:1}, {col:1}, {col:1}, {col:3}, {col:3}, {col:9}, {col:12}, {col:13} ];
var current = 0;
var prevEl = -1;

for (var i = 0; i < arr.length; i++) {
    var el = arr[i].col;
    arr[i].col = el > prevEl ? ++current : current;
    prevEl = el;
}

console.log(arr);

Upvotes: 3

madox2
madox2

Reputation: 51841

You can reduce your array:

var data = [
    { col: 1 }, { col: 1 },
    { col: 1 }, { col: 3 },
    { col: 3 }, { col: 9 },
    { col: 12 }, { col: 13 }
];

var result = data.reduce(function(r, i) {
    r.previous !== i.col && r.newValue++;
    r.previous = i.col;
    r.arr.push({ col: r.newValue });
    return r;
}, {arr: [], newValue: 0}).arr;

console.log(result);

I suppose your array is sorted by col, otherwise you need to sort it first.

Upvotes: 1

Michael J Caboose
Michael J Caboose

Reputation: 191

You could run a for loop to iterate through your array, and have if clauses to check for certain values; say the array object is called myArray:

var myArray = [ {col:1} {col:1} {col:1} {col:3} {col:3} {col:9} {col:12} {col:13} ];

for ( var i = 0; i < myArray.length; i++){
    if ( myArray[i] === 3 ){
        myArray[i] = 2;
    }
    // and so on.....
}

Upvotes: -1

Related Questions