-1

I tried to counts the same values in object and arrays, and it should show the first numbers which show off in arrays to country it in object here is my wrong code and example case:

let index = {};
let result = [];
const arrayList = [{
  "code": 101,
  "name": "banana",
  "price": 1000
}, {
  "code": 4,
  "name": "bluebberries",
  "price": 3000
}, {
  "code": 900,
  "name": "apple",
  "price": 300
}];
 
  // here is value of code in object list
const userChoose = [900, 900, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101];




userChoose.forEach(ar => {
  arrayList.forEach(point => {
    let key = ar;
    if (key in index) {
      index[key].count++;
    } else {
      let newEntry = {
        id: point.code,
        count: 1
      };
      index[key] = newEntry;
      result.push(newEntry);
    }

  })
});
console.log(result);

the output is not same like I wanted like this :

// final result:
[
  {
    "id": 900,
    "count": 2
  },
  {
    "id": 101,
    "count": 11
  }
]
poppop
  • 137
  • 13
  • I don't understand what you're trying to achieve from your description. Can you explain what the data in `array` is, what the numbers in `arr` represent, and what you're actually trying to compute? – Mike 'Pomax' Kamermans Jan 19 '19 at 02:03
  • I edited the variable, the array is the list and the arr is the user choose which number they want from the object list code:D – poppop Jan 19 '19 at 02:06
  • What does `arrayList` do for this question? I don't see how it's involved at all. – connexo Jan 19 '19 at 02:07
  • that is a list of menu, price and code, so on that `userCHoose` are a code they pick and we should check those `userChoose` in `arrayList`, so if the code in array list same like the userChoose, we count it how many it show offs / pick – poppop Jan 19 '19 at 02:09
  • yes correct., I edited it :D – poppop Jan 19 '19 at 02:11
  • 1
    Question is too similar to this one: https://stackoverflow.com/questions/54258215/how-to-count-duplicate-values-object-to-be-a-value-of-object – Shidersz Jan 19 '19 at 03:19

1 Answers1

0

I think this is what you are looking for.

let index = {};
let result = [];
const arrayList = [{
  "code": 101,
  "name": "banana",
  "price": 1000
}, {
  "code": 4,
  "name": "bluebberries",
  "price": 3000
}, {
  "code": 900,
  "name": "apple",
  "price": 300
}];
 
  // here is value of code in object list
const userChoose = [900, 900, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101, 101];


userChoose.forEach(item => {
  if(result.some(i => i.id === item) === false) {
    let obj = arrayList.find(e => e.id === item);

    result.push({ 
      id: item,
      count: 0
    });
  }
  result.find(r => r.id === item).count++;
});

console.log(result);
Bibberty
  • 4,670
  • 2
  • 8
  • 23