Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

From array of Object , get array of only matched key value

Suppose I have an array of object:

var students = [{name: 'Nick',achievements: 158,points: 1473}, {name: 'Nick',achievements: '175',points: '16375'}, 
{name: 'Ramon',achievements: '55',points: '2025'}];

I want to extract points from name Nick only in an array.

Like if (name=='Nick), O/P should be [1473,16375]

I tried:

var arrayPoints = students.map(function (el) { 
    if(el.name=='Nick'){
        return el.points
    }
});

But it gives me o/p:

console.log(arrayPoints)

[1473,16375,undefined] o/p
like image 269
Siva Pradhan Avatar asked Feb 16 '21 08:02

Siva Pradhan


2 Answers

A look to the methods:

  • Array#map returns a (new) value for each element.

  • Array#filter returns exactly the element if the return value of the callback is truthy


You could take two steps, one for filtering the items and another to get the values from.

const
    students = [{ name: 'Nick', achievements: 158, points: 1473 }, { name: 'Nick', achievements: '175', points: '16375' }, { name: 'Ramon', achievements: '55', points: '2025' }],
    arrayPoints = students
        .filter(student => student.name === 'Nick') 
        .map(student => student.points);

console.log(arrayPoints);

If Array#flatMap is implemented, you could take a single loop and filter and return a value.

The empty array has no items and this array is a neutral value which does not turn up in the result array.

const
    students = [{ name: 'Nick', achievements: 158, points: 1473 }, { name: 'Nick', achievements: '175', points: '16375' }, { name: 'Ramon', achievements: '55', points: '2025' }],
    arrayPoints = students
        .flatMap(student => student.name === 'Nick'
            ? student.points
            : []
        );

console.log(arrayPoints);
like image 172
Nina Scholz Avatar answered Nov 12 '22 03:11

Nina Scholz


For single loop result without undefined. You could do with Array#reduce

students.reduce(function (acc,el) { 
    if(el.name=='Nick'){
        acc.push(el.points)
    }
    return acc
},[]);
like image 22
prasanth Avatar answered Nov 12 '22 04:11

prasanth