When filtering the indices and accessing the same Dice in another vector nothing appears on the screen. Javascript

Asked

Viewed 20 times

-2

var codigo = [1,2,3,4,5,6,7,8,9,10]
var veiculos = [1000,2000,10000,5000,12958,502,985,125,967,1500]
var acidentes = [500,123,1500,350,600,25,15,20,129,159]

var indices = []

var teste = veiculos.filter((carro, index) => { //retorna o indice de veiculos menor que 2000
    if (carro < 2000) {
     indices.push(index)
    }

  })

res.innerHTML += `<p>indices do vetor veiculos com carros menor que 2000: ${indices}, </p>`// mostra todos os indices

var novoAci = []

var teste2 = acidentes.filter((acidente, index) => { //retorna o os acidentes se o index for igual ao indice
  if (index == indices) {
   novoAci.push(acidente)
  }

})


res.innerHTML += `<p>Acidentes com veículos menor que 2000: ${novoAci}, </p>`// não mostra nada na tela
  • it is not returning pq you are comparing an array with a number in teste2

1 answer

0


The problem is due to your comparison index == indices as indices is an array and index an int, it returns false and not the push in its array novoAci

to fix this you can make a map in indices and compare the value in indices with the value of index

var codigo = [1,2,3,4,5,6,7,8,9,10]
var veiculos = [1000,2000,10000,5000,12958,502,985,125,967,1500]
var acidentes = [500,123,1500,350,600,25,15,20,129,159]

var indices = []

var teste = veiculos.filter((carro, index) => { //retorna o indice de veiculos menor que 2000
    if (carro < 2000) {
     indices.push(index)
    }

  })

var novoAci = []

var teste2 = acidentes.filter((acidente, index) => { //retorna o os acidentes se o index for igual ao indice
indices.map((i)=>{
	if (index == i) {
   		novoAci.push(acidente)
  	}
})
  

})

console.log(novoAci)

You could also get the same result without the need to make a filter, making a map in indices and doing the push in novoAci taking the value of acidentes thus:

indices.map(i=>{ 
    novoAci.push(acidentes[i])
 })

Browser other questions tagged

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