property map ()


I'm learning how to program in javaScript I was trying to do an exercise where I had to sort the numbers in an array and then delete the ones that are repeated, do the following (I'll leave it below to continue with the explanation), my question is that I did not want to use a loop if I did not use map () to traverse the array but I did not know how to change the position of the array elements to make this comparison number.sort()[i] != number.sort()[i-1] and be able to store in a new array only one value, the truth I do not know if you can if someone knows

Sorry if I could not explain myself well

using a loop instead of map ():

var number = [1, 9, 3, 1, 7, 4, 6, 6, 7];

var arr = []
var k = 0;

for( let i = 0; i < number.length; i++){

    if(number.sort()[i] != number.sort()[i-1]){

        arr[k] = number.sort()[i]



note: later I realized that I could use set ().

asked by Carlos Puente 19.04.2018 в 06:47

2 answers


I give you an example of how I would use the map, although I tell you that it is not the best option because the map is used to transform the entire list that will be traversed, and in this case you want to eliminate data from that list .

listaOrdenada = []
number.sort() => {
    if (listaOrdenada.includes(numero) === false) {

We use map to go through all the elements of the list, and we check if those elements exist in the ordered list, if they do not exist they are added. And I tell you that it does not seem like a good option because map returns a list and in this case it would return a list of undefined.

A better option would be to use filter, since this one is designed to eliminate elements from the list, I'll give you an example of what it would be like:

number = number.filter((numero,indice) => {return number.indexOf(numero) == indice;})

In this case, indexOf returns the index of the first element that we find with the number value and if it is equal to the number we are checking, it adds it to the list otherwise it discards it.

I hope it serves you. Greetings.

answered by 19.04.2018 / 10:28

To scroll through an array you also have the option that ecmascript 2015 contemplates to use: for (let x of collection) . x is a variable that you create for the elements of the array collection let collection is an example. It is an array in which I go introduction elements after created. let colection = [] collection.push(new Pakiman ('Cauchin', 100, 30)) collection.push(new Pakiman ('Pokacho', 80, 50)) collection.push(new Pakiman ('Tocinauro', 150, 40)) for (let x of colection) { x.mostrar()} Instead of of you can use in everything depends on whether we need to show the index of an object, it would be valid with "in" If we want to show the whole object, we use "of" And with that you could choose the numbers to be deleted.

answered by 19.04.2018 в 09:52