Answer the question
In order to leave comments, you need to log in
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) );
Answer the question
In order to leave comments, you need to log in
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.
strings.reduce(function(p, v) {
if (-1 === p.indexOf(v)) {
p.push(v);
}
return p;
}, []);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question