G
G
gleendo2015-01-25 12:06:46
JavaScript
gleendo, 2015-01-25 12:06:46

How to understand the moment of solving a problem in JS?

Again, not a very clear moment in solving a problem in JS.
Task :
Let strings be an array of strings.
Write a unique(strings) function that returns an array containing only the unique elements of arr.
Decision:

function enique(arr) {
  var obj = {};

  for (var i = 0; i < arr.length; i++) {
    var str = arr[i];
    obj[str] = true;
  }

  return Object.keys(obj);
}

var strings = [1, 1, 1, 1, 1, 2, 3, 4, 5, 4, 4, 4, 4];

console.log( enique(strings) );

And so this line obj[str] = true is not so clear here; Explain, please.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Armenian Radio, 2015-01-25
@gbg

An associative array is created with strings as keys. Since the keys in such an array are unique, when a repeated row occurs in the source data, a new element of the obj array is not created, but simply overwritten by the previously created one. The result of the work of the subroutine is an array of keys of the obj array, which are unique strings.

A
Alexey Yakhnenko, 2015-01-25
@ayahnenko

strings.reduce(function(p, v) {
  if (-1 === p.indexOf(v)) {
    p.push(v); 
  } 
  return p; 
}, []);

M
maaGames, 2015-01-25
@maaGames

The programmer does not know how to Set, so he uses an associative container.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question