javascript array - increment value at given key

I have a dynamic array and I am trying to increment the value by 1 if the key exists in the array. According to my debug it is incrementing the key and and creating a second key/value pair.

A snippet of my code:

        for (var i = 0; i < choices.length; i++) {
            console.log(choices[i]);
            if (choices[i].YearTermId == 1) {
                if (!lookup(firstChoice, choices[i].FirstChoiceOptionId)) {
                    firstChoice.push({
                        key: choices[i].FirstChoiceOptionId,
                        value: 1
                    });
                } else {
                    firstChoice[choices[i].FirstChoiceOptionId] = firstChoice[choices[i].FirstChoiceOptionId] + 1;
                }

more if/else..

    function lookup( arr, name ) {
        for(var i = 0, len = arr.length; i < len; i++) {
            if( arr[ i ].key === name )
                return true;
        }
        return false;
    }

Answers 1

  • You're using an array where you should be using an object. If you use an object, your code can be rewritten as:

    var firstChoice = {};
    
    for (var i = 0; i < choices.length; i++) {
        var firstChoiceOptionId = choices[i].FirstChoiceOptionId;
    
        if (choices[i].YearTermId == 1) {
            firstChoice[firstChoiceOptionId] = firstChoice[firstChoiceOptionId]
                    ? firstChoice[firstChoiceOptionId] + 1
                    : 1;
    
            /* ... */
        }
    }
    

    If you need the data as an array afterwards, just map it:

    var firstChoiceArray = Object.keys(firstChoice).map(function(key) {
        return {
            key: key,
            value: firstChoice[key]
        };
    });
    

    Conversely, if you have an input array and want to convert it to an object for manipulation, reduce it:

    var firstChoice = firstChoiceArray.reduce(function(result, current) {
        result[current.key] = current.value;
    
        return result;
    }, {});
    

Related Articles