Skip to content
Advertisement

Javascript check if value exists in 2d array update else create

I’m creating a 2d array for a Google pie chart
The array has to be in the format

[
  //category, value
   [2,     11],
   [5,      2],
   [6.6,    2],
   [7.7,    2],
   [8.8,    7]
]

What I’m trying to get is a function where the category is passed to the function. If the category exists the value increments with 1 (value++). If it doesn’t, the record should be created with a value of 1.
There are partial solutions on the interwebs I found for this but I can’t seem to manage to get one working.
I think I’m close but I’m creating infinite loops. If someone could point me in the right direction that would be great! (no need to use this as a basis, I just need a simple and clear working function)

var array = [];

function updateArray(category) {
    for (var z = 0; key = array[z]; z++) {
        if (key.includes(category)) {
            var value = key[1];
            key[1] = [ category, value++ ];
            console.log("category updated");
        } else {
            array.push( [ category, 1 ]);
            console.log("category created");
        }
    }
}

EDIT: At first the array is empty.
I then read every record in the localstorage that matches a date format key (DD-MM-YYYY), no issues here.
When encountering for example 5 in one of the fields for a key the array should look like this:

[
  [5, 1]
]

When additionally encountering a 5, a 6, a 10 and a 5 this should be the result:

[
  [5, 3],
  [6, 1],
  [10, 1]
]

Hope this makes it more clear.

Advertisement

Answer

There are a couple of problems there:

  1. You’re looking for category anywhere in key, but you’ve said only the first entry in the subarrays is for the category (the second is for the value).

  2. You’e updating key[1] with a new array, not just an updated value.

  3. You’re pushing to the array you’re looping through if a key doesn’t include the category, so assuming the category isn’t in the first array you check, you’ll never find it and have an infinite loop.

I’d break it up into parts:

  • Find the entry, then
  • Either update it or add one if there isn’t one
function updateArray(category) {
    const entry = array.find(([cat]) => cat === category);
    if (entry) {
        // Update the value
        ++entry[1];
        console.log("category updated");
    } else {
        // Add a new entry
        array.push([category, 1]);
        console.log("category created");
    }
}

Live Example:

const array = [
  //category, value
   [2,     11],
   [5,      2],
   [6.6,    2],
   [7.7,    2],
   [8.8,    7]
];
function updateArray(category) {
    const entry = array.find(([cat]) => cat === category);
    if (entry) {
        // Update the value
        ++entry[1];
        console.log("category updated");
    } else {
        // Add a new entry
        array.push([category, 1]);
        console.log("category created");
    }
}

console.log("Before:", JSON.stringify(array, null, 4));
updateArray(5); // Updates the second entry in the array
console.log("After: ", JSON.stringify(array, null, 4));

Side note: I’d also suggest passing array into the function so that it’s reusable, rather than closing over array.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement