-3

I found this answer on how to map over an array to create ids Add id to array of objects - Javascript for each object in the array, but I was wondering how you'd adapt this code to create a sequence of ids for every group of another value:

let dataset = [
 {value: "a"},
 {value: "a"},
 {value: "a"},
 {value: "b"},
 {value: "b"},
 {value: "c"},
]

becomes:

[
 {value: "a", groupid: 1},
 {value: "a", groupid: 2},
 {value: "a", groupid: 3},
 {value: "b", groupid: 1},
 {value: "b", groupid: 2},
 {value: "c", groupid: 1},
]

Any help appreciated!

MayaGans
  • 1,815
  • 9
  • 30

2 Answers2

1

Here is the solution using traditional for loop.

var data = [
 {value: "a"},
 {value: "a"},
 {value: "a"},
 {value: "b"},
 {value: "b"},
 {value: "c"}
]

var id = 1;
var i ;
for(i=0;i<data.length-1;i++){
  var currValue = data[i].value;
  var nextValue = data[i+1].value;
  if(currValue===nextValue){
    id=id+1;
  }
  else {
    id = 1;
  }
    data[i].groupid=id;

}
data[i].groupid=id;
console.log(data);
Harmandeep Singh Kalsi
  • 3,315
  • 2
  • 14
  • 26
1

The foreach() method executes a provided function once for each array element, but returns undefined (see here). You could use the map() method (see here).

A working example would be:

let dataset = [{
    value: "a"
  },
  {
    value: "a"
  },
  {
    value: "a"
  },
  {
    value: "b"
  },
  {
    value: "b"
  },
  {
    value: "c"
  },
];

const counterMap = new Map();

let res = dataset.map((val) => {
  const previousGroupId = counterMap.get(val.value);
  let groupId;
  if (previousGroupId === undefined) {
    groupId = 1;
  } else {
    groupId = previousGroupId + 1;
  }
  counterMap.set(val.value, groupId);
  return {
    value: val.value,
    groupId: groupId
  };
});

console.log(res)