fetching specific object from array

Tags: ,



In following example I am trying to get specific object from an array.First I am checking if it is there using find and after that getting only that object.

const ppl = [
    { name: "emily", no: 1 },
    { name: "lily", no: 3 },
    { name: "sofeey", no: 5 }
];

function checkCoustomerNo(accNo) {
    return accNo.no === 1;
}
console.log(ppl.find(checkCoustomerNo).no + " " + "is avaiable");


function filterByValue(ppl, no) {
    return arr.filter(function (val) {
        return val[no] == 1;
    });
}

filterByValue(ppl, no); 

Answer

Fixed it in below snippet. Check it out.

const ppl = [
    { name: "emily", no: 1 },
    { name: "lily", no: 3 },
    { name: "sofeey", no: 5 }
];

function checkCoustomerNo(accNo) {
    return accNo.no === 1;
}
console.log(ppl.find(checkCoustomerNo).no + " " + "is avaiable");


function filterByValue(arr, no) {
    return arr.filter(function (val) {
        return val.no == no;
    });
}

console.log(filterByValue(ppl, 1)); 


Source: stackoverflow