-1

I want to increase the value depending on the key name. I have an array with scores:

[50,50,60,70,80,90,90,100]
Grade A: score<100 and score>=90
Grade B: score<90 and score>=80
Grade C: score<80 and score>=60
Grade D: score<60 and score>=0

In the end, I want to get an object with countable scores:

{A:0, B:0, C:0, D:0 };
Sweet Caramel
  • 206
  • 2
  • 11
  • it will only increase by one each time – Sweet Caramel Sep 25 '21 at 20:54
  • 2
    Which properties are you trying to increment and why? – Spectric Sep 25 '21 at 20:55
  • 1
    Familiarize yourself with [how to access and process nested objects, arrays or JSON](/q/11922383/4642212) and use the available static and instance methods of [`Object`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#Static_methods) and [`Array`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array#Static_methods). – Sebastian Simon Sep 25 '21 at 20:56
  • 1
    how are the keys related? please add the wanted result. – Nina Scholz Sep 25 '21 at 20:56
  • I have added more information and am awaiting approval – Sweet Caramel Sep 25 '21 at 21:21
  • [Duplicate](//google.com/search?q=site%3Astackoverflow.com+js+count+all+grades+based+on+array+of+points) of [categorizing and counting numbers in for loop - Javascript](/q/28599961/4642212). – Sebastian Simon Sep 25 '21 at 21:40
  • function countGrade(scores){ let table = {S:0, A:0, B:0, C:0, D:0, X:0}; S: table.S+=scores.filter((x=>x===100)).length; A: table.A+=scores.filter((x=>x<100&&x>=90)).length; B: table.B+=scores.filter((x=>x<90&&x>=80)).length; C: table.C+=scores.filter((x=>x<80&&x>=60)).length; D: table.D+=scores.filter((x=>x<60&&x>=0)).length; X: table.X+=scores.filter((x=>x === -1)).length; return table } – Sweet Caramel Sep 26 '21 at 17:38

1 Answers1

1

You could take a Proxy and change dependent properties.

const
    table = { S: 0, A: 0, B: 0, C: 0, D: 0, X: 0 },
    change = new Proxy(table, {
        set: function(obj, prop) {
            if (prop === 'B') obj.S++;
            obj[prop]++;
            return true;
        },
    });

change.B++;

console.log(table);
Spectric
  • 30,714
  • 6
  • 20
  • 43
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392