-1

My problem:

var rawData = [[two],[three],[four],[one],[two],[two],[two],[three],[four],[five],[three],[four],[five]];

Suppose I have this arrays of array from where I have to find the unique elements of an array and total count of that unique element in the array in the form of two respective arrays such as

var queslist = [one,two,three,four,five...]
var count = [countOfOne, countOfTwo, countOfThree, countOfFour, countOfFive...]

(Keep in mind the rawData is dynamic as Im getting the data from a large spreadsheet) What should be the best approach to achieve this?

JustCurious
  • 344
  • 5
  • 15

1 Answers1

1

Perhaps like this? Both examples can also be done with reduce which I find harder to read.

let list = {}
const rawData = ["two","three","four","one","two","two","two","three","four","five","three","four","five"]
  .forEach(item => {
    const obj = list[item] || { count: 0 };
    obj.count = obj.count ? obj.count + 1 : 1;
    list[item] = obj;
  });


 ["one","two","three","four","five"].forEach(item => console.log(item,list[item]))

Ignoring stuff not in the compare arrray

let list = {}
const compareList  = ["two","three"];
const rawData = ["two","three","four","one","two","two","two","three","four","five","three","four","five"]
  .forEach(item => {
    if (compareList.indexOf(item) !=-1) {
      const obj = list[item] || { count: 0 };
      obj.count = obj.count ? obj.count + 1 : 1;
      list[item] = obj;
    }
  });


 console.log(list)
mplungjan
  • 169,008
  • 28
  • 173
  • 236