Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
369 views
in Technique[技术] by (71.8m points)

javascript - how to count duplicate values object to be a value of object

how to count the value of object in new object values lets say that i have json like this :

let data = [{
    no: 3,
    name: 'drink'
  },
  {
    no: 90,
    name: 'eat'
  },
  {
    no: 20,
    name: 'swim'
  }
];

if i have the user pick no in arrays : [3,3,3,3,3,3,3,3,3,3,3,90,20,20,20,20]

so the output should be an array

[
 { 
   num: 3,
   total: 11
 },
 {
   num: 90,
   total: 1
 },
 {
   num:20,
   total: 4
 }

];

I would like to know how to do this with a for/of loop

Here is the code I've attempted:

let obj = [];
for (i of arr){
  for (j of data){
    let innerObj={};
    innerObj.num = i
    obj.push(innerObj)
  } 
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

const data = [{"no":3,"name":"drink"},{"no":90,"name":"eat"},{"no":20,"name":"swim"}];
const arr = [3,3,3,3,3,3,3,3,3,3,3,20,20,20,20,80,80];
const lookup = {};

// Loop over the duplicate array and create an
// object that contains the totals
for (let el of arr) {

  // If the key doesn't exist set it to zero,
  // otherwise add 1 to it
  lookup[el] = (lookup[el] || 0) + 1;  
}

const out = [];
// Then loop over the data updating the objects
// with the totals found in the lookup object
for (let obj of data) {
  lookup[obj.no] && out.push({
    no: obj.no,
    total: lookup[obj.no]
  });
}

document.querySelector('#lookup').textContent = JSON.stringify(lookup, null, 2);
document.querySelector('#out').textContent = JSON.stringify(out, null, 2);
<h3>Lookup output</h3>
<pre id="lookup"></pre>

<h3>Main output</h3>
<pre id="out"></pre>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...