Returning First X Items from Array

Returning first x items from array

array_slice returns a slice of an array

$sliced_array = array_slice($array, 0, 5)

is the code you want in your case to return the first five elements

How to get first N number of elements from an array

I believe what you're looking for is:

// ...inside the render() function

var size = 3;
var items = list.slice(0, size).map(i => {
return <myview item={i} key={i.id} />
});
return (
<div>
{items}
</div>
)

Javascript Array - get first 10 items

This will do the job. Replace [startIndex] and [endIndex] with 0 and 10 to get the first 10.

data.slice([startIndex], [endIndex]).map((item, i) => {
placeIDs.push(item.place_id);
});

Use Array.filter to return values for a set number of items

The shortest way to do this is using Array.slice:

const myArray = [
{ url: "example.com/1" },
{ url: "example.com/sdf" },
{ url: "example.com/blue" },
{ url: "example.com/foo" },
{ url: "example.com/123" },
]

const limit = 3
const shorterArray = myArray.slice(0, limit).map(item => item.url)

console.log(shorterArray)

How to return first 5 objects of Array in Swift?

By far the neatest way to get the first N elements of a Swift array is using prefix(_ maxLength: Int):

let array = [1, 2, 3, 4, 5, 6, 7]
let slice5 = array.prefix(5) // ArraySlice
let array5 = Array(slice5) // [1, 2, 3, 4, 5]

the one-liner is:

let first5 = Array(array.prefix(5))

This has the benefit of being bounds safe. If the count you pass to prefix is larger than the array count then it just returns the whole array.

NOTE: as pointed out in the comments, Array.prefix actually returns an ArraySlice, not an Array.

If you need to assign the result to an Array type or pass it to a method that's expecting an Array param, you will need to force the result into an Array type: let first5 = Array(array.prefix(5))

remove first element from array and return the array minus the first element

This should remove the first element, and then you can return the remaining:

var myarray = ["item 1", "item 2", "item 3", "item 4"];    myarray.shift();alert(myarray);

Get the first N elements of an array?

Use array_slice()

This is an example from the PHP manual: array_slice

$input = array("a", "b", "c", "d", "e");
$output = array_slice($input, 0, 3); // returns "a", "b", and "c"

There is only a small issue

If the array indices are meaningful to you, remember that array_slice will reset and reorder the numeric array indices. You need the preserve_keys flag set to trueto avoid this. (4th parameter, available since 5.0.2).

Example:

$output = array_slice($input, 2, 3, true);

Output:

array([3]=>'c', [4]=>'d', [5]=>'e');


Related Topics



Leave a reply



Submit