Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A good way to associate a counter to each member of an array in Javascript?

Tags:

javascript

I have an array of strings in Javascript like `var elements = ["string1", "string2"]; The array is created dynamically so it could contain any number of strings. I want to associate a counter to each element of the array. The counter will increment or decrement during the webpage's life.

I was going to try element["string1"].counter = 1; but it didn't work.

What's a good way to implement this?

like image 237
Tony_Henrich Avatar asked Dec 11 '25 04:12

Tony_Henrich


2 Answers

If you had an array var elements = ["string1", "string2"], you could not access an element with elements["string1"], you are using the value not the index. elements[0] is the correct form of access to the element, using the numerical key.

Even then, strings are special types of object and do not appear to take additional parameters readily, at least not when I tested a moment ago. Which is odd.

You could quickly knock the array in to a set of objects with separate text and counter components.

var elements = ["string1", "string2"];
var elementsWithCounter = [];

for(var index = 0; index < elements.length; index++) {
    elementsWithCounter[i] = { text: elements[index], counter: 1 };
}
like image 54
Orbling Avatar answered Dec 12 '25 18:12

Orbling


You could also create a "hash table" using a plain object such as:

var counter = {};

for(var i = elements.length; i--; ) {
    counter[elements[i]] = 1;
}

Then you could increment the counter with:

counter['string1'] += 1;

or

counter[elements[0]] += 1;
like image 34
Felix Kling Avatar answered Dec 12 '25 17:12

Felix Kling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!