How to truncate an array of objects in javascript
Let's say you call an api route to get a list of users. But you really only want the 3 most recent users.
[
{
id: 1,
name: 'Wes'
},
{
id: 2,
name: 'Molly'
},
{
id: 3,
name: 'Cole'
},
{
id: 4,
name: 'James'
}
{
id: 5,
name: 'Robert'
}
// so on
]
You can use the .slice
method in JavaScript to truncate the array down to 3 user objects.
const allUsers = await fetch(`/api/get-users`)
const sliceUsers = allUsers.slice(0, 3); // get first 3 users
console.log(sliceUsers);
// result
[
{
id: 1,
name: 'Wes'
},
{
id: 2,
name: 'Molly'
},
{
id: 3,
name: 'Cole'
}
]