0
var food = ["fruit=apple", "fruit=banana", "drink=cola"];
var vars = [];
for(var i = 0; i < food.length; i++)
{
    var key = food[i].substring(0, food[i].indexOf("="));
    if (vars[key] == undefined){
        vars[key] = [];
    }
    vars[key].push(food[i].toLowerCase().split("=")[1]);
}
console.log(vars);
console.log(vars.length);

The output from the above code will output this. But the problem is that the length: 0. I don't understand how that is even possible, because you can clearly see that the array containing [fruit: Array(2), drink: Array(1)]. But still it says length: 0;

The output of vars and vars.length

I want to loop through the vars array with a for loop, but I can't because I cannot use the vars.length in my for loop.

Or maybe there is a other way to loop through the vars anny suggestions are welcome.

3
  • What should the length be? 2, because of the number of keys, 3, because of the total number of items, or something else? Commented Dec 2, 2017 at 21:18
  • yes it need to be 2. I also need the keywords to be the index so if say food[fruit].length I want to see how many items there are in the fruit array that is inside of the food array. Commented Dec 2, 2017 at 21:21
  • 1
    Right, so just use an object {}, and use @hsz's solution to get the length. Commented Dec 2, 2017 at 21:22

1 Answer 1

2

You are using your vars array as an object. Arrays don't have literal keys. With your approach, you can count your values using:

Object.values(vars).length
Sign up to request clarification or add additional context in comments.

Comments

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.