1

input: arbitrary array

output: unique elements and their count

So far I was able to find the unique elements but I can't figure it out how to correlate them with the count for each element. Any suggestions(without using functions if possible - just started and didn't get to functions yet)?

var arr = [3, 4, 4, 3, 3];
var new_arr = [];
for (i = 0; i < arr.length; i++) {
  if (new_arr.includes(arr[i])) {
    // pass
  } else {
    new_arr.push(arr[i]);
  }
}
console.log(new_arr);
Sami
  • 45
  • 4
  • 1
    in that one the solution was: the count for one specific element(you knew the element) OR they were using methods – Sami Nov 22 '18 at 20:25

1 Answers1

1

Use an Object instead of an Array to keep track of the count. The key is the number in question and its value is the count.

Use Array#reduce

const res = [3, 4, 4, 3, 3].reduce((acc,cur)=>{
  
  if(acc[cur]) acc[cur]++;
  else acc[cur] = 1;
  return acc;

}, {});

console.log(res);

Or without any methods:

var arr = [3, 4, 4, 3, 3];
var new_arr = {};
for (i = 0; i < arr.length; i++) {
  if (new_arr[arr[i]]) {
    new_arr[arr[i]]++;
  } else {
    new_arr[arr[i]] = 1;
  }
}
console.log(new_arr);
kemicofa ghost
  • 16,349
  • 8
  • 82
  • 131