Form into a single array after iterating an object

How to get values of views into single array and get the two largest values in that array. The below is not creating single array. Could someone please advise ?

const data = [
{
id: 1,
views: 5678,
textData: "Sun"
},
{
id: 2,
views: 2500,
textData: "Moon"
},
{
id: 3,
views: 3500,
textData: "Earth"
},
{
id: 4,
views: 1250,
textData: "Sky"
}
]

data.map(({id, views, textData}) =>{
let myArr = [];
myArr.push(views);
let result = Math.max(...myArr);
console.log(result); 
})

Desired Array: [5678, 2500, 3500, 1250 ]
Final Output : [5678,3500 ]

>Solution :

You can use Array#map to create an array of the views properties, then sort it.

const data=[{id:1,views:5678,textData:"Sun"},{id:2,views:2500,textData:"Moon"},{id:3,views:3500,textData:"Earth"},{id:4,views:1250,textData:"Sky"}];
let res = data.map(x => x.views).sort((a,b) => b - a).slice(0, 2);
console.log(res);

Leave a Reply