It is returning the data below 2000, but I need to know what positions this data is in. Javascript

Asked

Viewed 37 times

2

var veiculos = [valores informados pelo usuário]

var teste = veiculos.filter(carro => carro <= 2000)

res.innerHTML += `${teste}, </br>

`

2 answers

0

You can pass a second parameter in the function that is passed as parameter in the filter to pick up the index. Example:

const veiculos = [9999, 1000, 2000, 3000, 4000, 5000];
const indexes = [];
var teste = veiculos.filter((carro, index) => {
  if (carro <= 2000) {
    indexes.push(index);
    return true;
  }
  
  return false;
});

console.log(teste, indexes);

  • I think the filter then it got kind of out of use not? Pq makes the filter, but, makes a if next.

  • @Leandrade, I guess you didn’t stay out of it, why? basically it executes a filter on top of an array returning a new array, i.e., we pass a predicate to the filter and in this predicate there is a filter with the if. Do you see another solution? suddenly I didn’t notice something.

0


Wellyngton,

Since you want to return the index, perhaps using the filter is not the best option, although it is possible.

See these examples, using reduce and also a more traditional for, both resulting in an array containing the indexes you want to filter:

let veiculos = [2001,2000,1999,3000,4000,1000,7000,8000,9999,100,500,300,800];

//Reduce
let indicesReduce = veiculos.reduce( (acumulador,carro, indice) => {
  if (carro <= 2000) {
    acumulador.push(indice);
  }
  return acumulador;
}, [] );

console.log("Reduce:", indicesReduce);

//For
let indicesFor = [];

for (const [indice,carro] of veiculos.entries()) {
  if(carro <= 2000) {
    indicesFor.push(indice);
  }
}

console.log("For:", indicesFor);

References:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

Browser other questions tagged

You are not signed in. Login or sign up in order to post.