0

Creating a function call frequency and passing an array. I'm taking the values that are in the array which are integers and storing them inside of an object and my end goal is to check the occurrence of every number that has been seen and if they been seen I will increase the count. Why are the property are set as strings?, how can I access the integers to increase the count. I want to increase my understanding of objects.

function frequency(array) {
  let object = {}
  let count = 0
  let num
  let temp = []
  for (var i = 0; i < array.length; i++) {
    num = array[i]
    object[num] = count++
      console.log(object);
  }
}
console.log(frequency([1, 2, 3, 4]));
David
  • 21,070
  • 7
  • 57
  • 113
  • Javascript object key-value pairs are stored as `string:any`, which is why the numbers you see are strings. You would increase the count by increasing the value of the specific key in the object. `if(typeof(object[num]) != "undefined")) object[num]++; else object[num] = 1;` – David Mar 02 '21 at 19:44
  • what is object[num]++ and why is object[num] = 1 being set to one? – Johnbel Mahautiere Mar 02 '21 at 19:57
  • The first increments the value and the second defines a default value if the number has not been added to the object yet. – David Mar 02 '21 at 19:58
  • Thank you but why are you checking typeof(object[num]) != "undefined" – Johnbel Mahautiere Mar 02 '21 at 20:00
  • Also, I thought objects were unordered, I'm not sure why it's the values are being ordered because I want the end of the check to not be ordered. – Johnbel Mahautiere Mar 02 '21 at 20:02
  • Javascript object properties are sorted based on the keys. [More here](https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order). However, I would say that's a bit of a misnomer, since object properties are accessed by key, and not by a numerical index. They do not conform to the order in which they were inserted into the object. – David Mar 02 '21 at 20:05

1 Answers1

0

Javascript object properties are string:any key-value pairs. You see your numbers as string keys because of this. When you set a property with an integer key (or any other non-string value), it is first converted into a string.

To get the correct count of occurrences of your numbers, you should be incrementing the key corresponding to the value, rather than just incrementing your count variable. I also added the typeof line to check and make sure that key-value pair has been previously set. If not, it creates one and gives it a value of 1, since this is the first time we've seen that number.

function frequency(array) {
  let object = {}
  let count = 0
  let num
  let temp = []
  for (var i = 0; i < array.length; i++) {
    num = array[i]
    if(typeof(object[num]) != "undefined")
      object[num]++;
    else
      object[num] = 1;
  }
  console.log(object);
}
frequency([1, 2, 3, 4, 4, 4, 3, 5, 1]);
David
  • 21,070
  • 7
  • 57
  • 113