billy
billy

Reputation: 1493

How does this code work that searches for multiple values in an array?

I was looking for a solution to finding multiple values in an array, and found this:

function find_duplicate_in_array(arra1) {
  var object = {};
  var result = [];

  arra1.forEach(function(item) {
    if (!object[item])
      object[item] = 0;
    object[item] += 1;
  })

  for (var prop in object) {
    if (object[prop] >= 2) {
      result.push(prop);
    }
  }
  return result;
}

console.log(find_duplicate_in_array([1, 2, -2, 4, 5, 4, 7, 8, 7, 7, 71, 3, 6]));

I don't understand what is happening. Specifically this:

object[item] = 0;
object[item] +=1;

So... for each element in the array, if the element is not in temporary object add element at index 0, and then +1?.

What's going on? Would someone please explain line by line. I am new to JavaScript.

Upvotes: 1

Views: 126

Answers (2)

sjahan
sjahan

Reputation: 5960

Here is the code, with each line commented! I hope it will help you ;)

function find_duplicate_in_array(arra1) {

  // Temporary count of each item in the input array/
  var object = {};
  // Final result containing each item that has been seen more than one time.
  var result = [];

  // For each item of the array...
  arra1.forEach(function (item) {
    // If it is not in the temporary object, initialize it to 0.
    if(!object[item])
      object[item] = 0;
    // Add one since we just have found it!  
    object[item] += 1;
  })


  // Now, every item of the input array has been counted in object.
  // For each item of object:
  for (var prop in object) {
    // If it has been counted more than one time, add it to the result.
    if(object[prop] >= 2) {
      result.push(prop);
    }
  }

  // Return the result.
  return result;

}

console.log(find_duplicate_in_array([1, 2, -2, 4, 5, 4, 7, 8, 7, 7, 71, 3, 6]));

The complexity here is on those lines:

if(!object[item])
  object[item] = 0;
object[item] += 1;

It is the same than the more stricter notation:

if(!object[item]) {
  object[item] = 0;
}
object[item] += 1;

If you don't set curly braces, only the next instruction will be executed!

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386756

Maybe you are missing the block statement { ... } of the if statement, which would be

if (!object[item]) {
    object[item] = 0;
}
object[item] += 1;

which means, if object[item] is not truthy, then assign zero to object[item].

Then increment this value.

if (!object[item])    // no block statement
    object[item] = 0; // then part finished with semicolon
object[item] += 1;    // code after the condition

The given code is a valid change of the above by taking only a single statement, which is finished with semicolon. In this case you do not need a block statement.

Upvotes: 1

Related Questions