Search code examples
javascriptarraysmappingincrement

How to have a number in an array that can edit according to edits(removal or adding)


Sorry for the badly explained title(really don't know any other way to put it). I have an array that needs an increment value:

const array = [
  {
    name: 'charmander',
    iv: '13;10;25;24;4;21',
    lvl: 23,
    nature: 'Rash',
    holding: '',
    mega: false
  },
  {
    name: 'bulbasaur',
    iv: '19;18;13;20;27;28',
    lvl: 17,
    nature: 'Brave',
    holding: '',
    mega: false
  }
];

I want to map the array into something where there is a number in each of the array, like:

const array = [
  {
    name: 'charmander',
    iv: '13;10;25;24;4;21',
    lvl: 23,
    nature: 'Rash',
    holding: '',
    mega: false,
    number: 1,
  }];

Although, I can't insert the number when Im adding stuff into the array as they may be deleted or removed, leaving a number gap. Is there any efficient way to do this?


Solution

  • // All your array initialization here
    
    // using simple cycle
    for (let i in array) {
      array[i].number = i;
    }
    
    // using foreach
    array.forEach((p, i) => { p.number = i; })
    
    // using map
    array = array.map((p, i) => { p.number = i; return p; });
    
    // dynamic association (if you later need to change the order)
    // this will automatically change if you sort your array or remove
    // some elements
    array.forEach(p => {
      Object.defineProperty(p, 'number', { get: () => array.indexOf(p) })
    })