Home > Net >  Form into a single array after iterating an object
Form into a single array after iterating an object

Time:01-31

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 ]

CodePudding user response:

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);

CodePudding user response:

Get result in one loop without sorting, but the code doesn't look very clean.

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"}];

const values1 = []
const values2 = [0, 0]
data.forEach(d => {
  values1.push(d.views)
  values2[0] = Math.max(values2[0], Math.min(d.views, values2[1]))
  values2[1] = Math.max(d.views, values2[1])
})

console.log('single values: ', values1)
console.log('two largest values: ', values2)
  • Related