2

I am trying to use a map to count duplicate string number in an array, my code:

var map = {};
var myarray = ["John", "John", "John", "Doe", "Doe", "Smith",
               "John", "Doe", "Joe"];

for (var a = 0; a < myarray.length; a++) {
    if (map[myarray[a]] !== null) {
        map[myarray[a]] += 1;
    } else {
        map[myarray[a]] = 1;
    }
}

but when I do console.log(map); it returns

Object {John: NaN, Doe: NaN, Smith: NaN, Joe: NaN}

Why it is NaN? I want to have the result like:

John :4, Doe: 3, Smith: 1, Joe: 1

How can I do? Thank you in advance.

2 Answers 2

1

map[myarray[a]] !==null will return true when the field is undefined, which is the case when first time encountering a new value.

Should be:

map[myarray[a]] !== undefined

or

map[myarray[a]] != null
// undefined == null 
Sign up to request clarification or add additional context in comments.

Comments

0

In this case you should not comapre with null strictly === because undefined is not equivalent to null. Try this:

if (map[myarray[a]] != null) {

or simply:

if (map[myarray[a]]) {

1 Comment

if (map[myarray[a]]) or map[myarray[a]] !== undefined works, thanks a lot:)

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.