0

I would like to know how many element of each number is in array, i. e.: [2,2,3,6,1,1001,2] should return 2 => 3, 3 => 1, 6 = >1, 1 => 1, 1001 => 1. But when I use additional array when I set counted[2] = 3, and counted[1001] = 1 I create 1002 length array (in opposite to arrays in PHP I think...). How could I improve it? (of course I don't know how many element there will be in my input array) Thanks in advice.

4 Answers 4

2

Use a Javascript object as a hashtable, so the numbers are represented as properties on that object:

var array = [2,2,3,6,1,1001,2];
var numbers = {};
for (var i = 0; i < array.length; i++) {
    var number = array[i];
    if (typeof(numbers[number]) === "undefined") {
        numbers[number] = 1;
    } else {
        numbers[number]++;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Nice, I was praying for that simple solution!
1

You could use objects.

Here is an example:

var src = [2,2,3,6,1,1001,2]
var results = {}

for (var i = 0, n = src.length; i < n; i++)
{
   results[src[i]] = results[src[i]] || 0
   results[src[i]] += 1
}

// Iterate over results or access by index to see frequency
for (var idx in results)
{
   console.log(idx + " ==> " + results[idx])
}

Comments

0

Try using Object instead of Array.

Array assumes that if you insert an element at index x, then it implies that you want an array of at least x length.

Comments

0

This is a very naive answer, but you could try using a hashmap instead.

var counted = { };

1 Comment

Example: var counted = { "2": 3, "1001": 1 }; console.log(counted["2"]); counted["3"] = 4;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.