Home > Blockchain >  JS Decrease property after specific value
JS Decrease property after specific value

Time:01-04

I have an array of objects, objects that contain an order: number; property.

I want for each object in that array that has the order property higher than a specific value to have it decreased it by one.

Any simple way to achieve this?

myArray.forEach(x => x.order >= someValue)...

CodePudding user response:

You can map the result, updating the value when >= someValue

const someValue = 3;

const result = [
  { order: 1 }, 
  { order: 2 }, 
  { order: 3 }, 
  { order: 4 }
].map(x => x.order >= someValue ? { ...x, order: x.order - 1 } : x);

console.log(result);

CodePudding user response:

With array.reduce

const value = 2;
const testArray = [{ order: 1 }, { order: 1 }, { order: 3 }];

const result = testArray.reduce((acc, curr) => {
  if (curr.order > value) {
    return [...acc, { ...curr, order: curr.order - 1 }];
  }
  return [...acc, curr];
}, []);
console.log(result);

CodePudding user response:

Several options to reach this:

  1. Adding functionality to Array.prototype.

    if(!Array.prototype.decreaseOrderIfBiggerThan) {
      Array.prototype.decreaseOrderIfBiggerThan = function(value) {
        if(!value || typeof value != 'number') return this;
        return this.map((el) => ({ 
          ...el, 
          order: el?.order > value ? --el.order : el.order 
        }))
      }
    }
    
  2. Simply mapping:

    myArray = myArray.map((el) => ({ 
      ...el, 
      order: el?.order > value ? --el.order : el.order 
    }))
    
  3. Mutating original array: it's basically #2 method but without assigning new array to original one and with forEach.

Hopes this is what you needed.

  • Related