I would like to know how to go through an array within another javascript array!

Asked

Viewed 704 times

2

Good night. I’m having trouble going through an array within another array, I’d like to select the user by the technology they use, in the CSS case. If there’s any way someone can give me a logic to understand and continue my studies. Thank you! Follow the program I’m doing, if someone has tips to improve, I’m still learning so excuse any mistake!

const usuarios = [
    { nome: 'Carlos', tecnologias: ['HTML', 'CSS'] },
    { nome: 'Jasmine', tecnologias: ['JavaScript', 'CSS'] },
    { nome: 'Tuane', tecnologias: ['HTML', 'Node.js'] }
]

function users(usuarios) {
    let i = 0
    for (let i = 0; i < usuarios.length; i++) {
        console.log(`${usuarios[i].nome} trabalho com ${usuarios[i].tecnologias}.`)
    }
}

function checaSeUsuarioUsaCSS(usuario) {
    usuario.Usacss = false
    if (usuarios.tecnologias == "css"){
        usuario.Usacss = true
    }
}  

for (let i = 0; i < usuarios.length; i++) {
    const usuarioTrabalhaComCSS = checaSeUsuarioUsaCSS(usuarios[i])

    if (usuarioTrabalhaComCSS) {
        console.log(`O usuário ${usuario[i].nome} trabalha com CSS`)
    }
}

console.table(usuarios)
checaSeUsuarioUsaCSS(usuarios)
users(usuarios)
  • Only that function checaSeUsuarioUsaCSS() is enough to be a solution?

  • I believe yes, would it be necessary more? I modified the program a lot trying to find some solution and got lost, in case there was a

  • 1

    I was preparing an answer, https://repl.it/repls/HideousShadySmalltalk, but if you have already solved your doubt. Do what? :)

  • Thanks for your help, I’ll look at your code

1 answer

3


In your code, you are checking whether the array complete is a string:

if (usuarios.tecnologias == "css") { /* ... */ }

This is incorrect because obviously a array will always be different from the CSS string. Moreover, you are not even able to compare two arrays with the same values using that operator, since comparing objects - which includes arrays - is made by reference, unlike primitives such as strings or numbers.

So to check whether the array has an element you want to search, use the method includes. So you can check whether the string CSS, a primitive, is contained in the array. Behold:

function checaSeUsuarioUsaCSS(usuario) {
  return usuario.tecnologias.includes('CSS');
}

const carlos = { nome: 'Carlos', tecnologias: ['HTML', 'CSS'] };
const tuane = { nome: 'Tuane', tecnologias: ['HTML', 'Node.js'] };

console.log(checaSeUsuarioUsaCSS(carlos)); // true
console.log(checaSeUsuarioUsaCSS(tuane)); // false

  • 1

    Grateful for the response, I will research on the . includes

Browser other questions tagged

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