Home > Software design >  How to Sort and Map an Array on Angular 7
How to Sort and Map an Array on Angular 7

Time:03-11

i have this array:

myArray = {
[0]{priority: 1, percent: 90, correct: true}
[1]{priority: 1, percent: 20, correct: true}
[2]{priority: 2, percent: 50, correct: true}
[3]{priority: 2, percent: 50, correct: true}
[4]{priority: 3, percent: 70, correct: true}
[5]{priority: 3, percent: 50, correct: true}
}

How can i add the percents by priority, and then change the value "correct" to "false" of all the results that gave me more than 100?

for example:

  • Priority 1 have 2 values: 90 and 20 = 110
  • Priority 2 have 2 values: 50 and 50 = 100
  • Priority 3 have 2 values: 70 and 50 = 120
  • So All objects of priority 1 should change value "correct" into "false"
  • All objects of priority 2 should change value "correct" into "correct"
  • All objects of priority 3 should change value "correcto" into "false

CodePudding user response:

     const myArray: { priority: number; percent: number; correct: boolean }[] = [
  { priority: 1, percent: 90, correct: true },
  { priority: 1, percent: 20, correct: true },
  { priority: 2, percent: 50, correct: true },
  { priority: 2, percent: 50, correct: true },
  { priority: 3, percent: 70, correct: true },
  { priority: 3, percent: 50, correct: true },
];
   




 const newArr = myArray
      .sort((a, b) => a.priority - b.priority)
      .map((val, i, myArray) => {
        const percentSum = myArray
          .filter((a) => a.priority == val.priority)
          .map((b) => b.percent)
          .reduce((a, b) => a   b, 0);
        const arrObj = {
          ...val,
          correct: percentSum > 100 ? false : true,
        };
        return arrObj;
      });

    console.log(newArr);

Output

[{
  correct: false,
  percent: 90,
  priority: 1
}, {
  correct: false,
  percent: 20,
  priority: 1
}, {
  correct: true,
  percent: 50,
  priority: 2
}, {
  correct: true,
  percent: 50,
  priority: 2
}, {
  correct: false,
  percent: 70,
  priority: 3
}, {
  correct: false,
  percent: 50,
  priority: 3
}]

CodePudding user response:

Providing a quick solution but there could be lot of better solutions as well :

myArray = [
{priority: 1, percent: 90, correct: true},
{priority: 1, percent: 20, correct: true},
{priority: 2, percent: 50, correct: true},
{priority: 2, percent: 50, correct: true},
{priority: 3, percent: 70, correct: true},
{priority: 3, percent: 50, correct: true},
];

tempMap = new Map();

myArray.forEach( (item) => {
  if(tempMap.has(item.priority)) {
    tempMap.set(item.priority, tempMap.get(item.priority)   item.percent);
  }
  else {
    tempMap.set(item.priority, item.percent);
  }
});

myArray.forEach( (item) => {
  item.correct = tempMap.get(item.priority) > 100 ? false : true;
});

console.log(myArray);

  • Related