understanding the filter method in javascript

2

I do not understand what exactly does this [0] in the filter method within the function getUsuario just want to see if you can clarify this doubt.

 'use strict'
const usuarios = [
{id:1, nombre:'ricardo', profesion_id: 1},
{id:2, nombre:'alejandro', profesion_id: 3},
{id:3, nombre:'diego', profesion_id: 2}
]

const profesion = {
1:'programador',
2:'diseñador',
3:'otro'
}

function getUsuarios(callback){
    setTimeout(() => {
    callback(null, usuarios)
    },1000)
}

function getUsuario(id, callback){
    setTimeout(() => {
        console.log(id)
    callback( null, usuarios.filter((usuario) => usuario.id === id)[0] )
    },1000)
}

function getProfesion(id, callback){
    setTimeout(() => {
    callback(null, profesion[id])
    },1000)
}

getUsuarios((err, usuarios) => {
    const alejandroId = usuarios[1].id;
    //const alejandroId1 = usuarios[1].nombre;
    //console.log(alejandroId1)
    getUsuario(alejandroId,(err, usuario) => {
        const profesionId = usuario.profesion_id;

        getProfesion(profesionId,(err, profesion) => {
            console.log('la profesion es de', /**alejandroId1**/ profesion)
        })
    })
})
    
asked by Rangel 06.08.2018 в 23:18
source

1 answer

1

The function filter() of javascript returns an array with all the elements of the array that meet certain conditions. By adding [0] you are accessing the first element of the returned array.

'use strict'
const usuarios = [
{id:1, nombre:'ricardo', profesion_id: 1},
{id:2, nombre:'alejandro', profesion_id: 3},
{id:3, nombre:'diego', profesion_id: 2}
]

const profesion = {
1:'programador',
2:'diseñador',
3:'otro'
}

function getUsuarios(callback){
    setTimeout(() => {
    callback(null, usuarios)
    },1000)
}

function getUsuario(id, callback){
    setTimeout(() => {
        console.log(id)
    callback( null, usuarios.filter((usuario) => usuario.id === id)[0] )
    },1000)
}

function getProfesion(id, callback){
    setTimeout(() => {
    callback(null, profesion[id])
    },1000)
}

getUsuarios((err, usuarios) => {
    const alejandroId = usuarios[1].id;
    //const alejandroId1 = usuarios[1].nombre;
    //console.log(alejandroId1)
    getUsuario(alejandroId,(err, usuario) => {
        const profesionId = usuario.profesion_id;

        getProfesion(profesionId,(err, profesion) => {
            console.log('la profesion es de', /**alejandroId1**/ profesion)
        })
    })
})
    
answered by 06.08.2018 / 23:21
source