Get the First N Elements of an Array

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

Use of array and a function to print first n elements in C [as like as sort(a+m, a+n)]

You can use pointers for such format

void print (int * begin, int * end){
while(begin != end){
printf("%d", *begin);
begin++;
}
}

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

Get first N elements from an array in BigQuery table

Here's a general solution with a UDF that you can call for any array type:

CREATE TEMP FUNCTION TopN(arr ANY TYPE, n INT64) AS (
ARRAY(SELECT x FROM UNNEST(arr) AS x WITH OFFSET off WHERE off < n ORDER BY off)
);

WITH data AS
(
SELECT 1001 as id, ['a', 'b', 'c'] as array_1
UNION ALL
SELECT 1002 as id, ['d', 'e', 'f', 'g'] as array_1
UNION ALL
SELECT 1003 as id, ['h', 'i'] as array_1
)
select *, TopN(array_1, 2) AS my_result
from data

It uses unnest and the array function, which it sounds like you didn't want to use, but it has the advantage of being general enough that you can pass any array to it.

Fastest way to get the first n elements of a List into an Array


Option 1 Faster Than Option 2

Because Option 2 creates a new List reference, and then creates an n element array from the List (option 1 perfectly sizes the output array). However, first you need to fix the off by one bug. Use < (not <=). Like,

String[] out = new String[n];
for(int i = 0; i < n; i++) {
out[i] = in.get(i);
}

return the first n elements of a k sized array in O(1) time

If you must work with raw arrays and not ArrayList then Arrays has what you need. If you look at the source code, these are the absolutely best ways to get a copy of an array. They do have a good bit of defensive programming because the System.arraycopy() method throws lots of unchecked exceptions if you feed it illogical parameters.

You can use either Arrays.copyOf() which will copy from the first to Nth element to the new shorter array.

public static <T> T[] copyOf(T[] original, int newLength)

Copies the specified array, truncating or padding with nulls (if
necessary) so the copy has the specified length. For all indices that
are valid in both the original array and the copy, the two arrays will
contain identical values. For any indices that are valid in the copy
but not the original, the copy will contain null. Such indices will
exist if and only if the specified length is greater than that of the
original array. The resulting array is of exactly the same class as
the original array.

2770
2771 public static <T,U> T[] More ...copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
2772 T[] copy = ((Object)newType == (Object)Object[].class)
2773 ? (T[]) new Object[newLength]
2774 : (T[]) Array.newInstance(newType.getComponentType(), newLength);
2775 System.arraycopy(original, 0, copy, 0,
2776 Math.min(original.length, newLength));
2777 return copy;
2778 }

or Arrays.copyOfRange() will also do the trick:

public static <T> T[] copyOfRange(T[] original, int from, int to)

Copies the specified range of the specified array into a new array.
The initial index of the range (from) must lie between zero and
original.length, inclusive. The value at original[from] is placed into
the initial element of the copy (unless from == original.length or
from == to). Values from subsequent elements in the original array are
placed into subsequent elements in the copy. The final index of the
range (to), which must be greater than or equal to from, may be
greater than original.length, in which case null is placed in all
elements of the copy whose index is greater than or equal to
original.length - from. The length of the returned array will be to -
from. The resulting array is of exactly the same class as the original
array.

3035    public static <T,U> T[] More ...copyOfRange(U[] original, int from, int to, Class<? extends T[]> newType) {
3036 int newLength = to - from;
3037 if (newLength < 0)
3038 throw new IllegalArgumentException(from + " > " + to);
3039 T[] copy = ((Object)newType == (Object)Object[].class)
3040 ? (T[]) new Object[newLength]
3041 : (T[]) Array.newInstance(newType.getComponentType(), newLength);
3042 System.arraycopy(original, from, copy, 0,
3043 Math.min(original.length - from, newLength));
3044 return copy;
3045 }

As you can see, both of these are just wrapper functions over System.arraycopy with defensive logic that what you are trying to do is valid.

System.arraycopy is the absolute fastest way to copy arrays.

jq: get first n elements of an array field

If you are looking to print only those specific fields on the first 3 results, use the slice operator. See jqplay for demo

.identifier[:3] | map({system, value})

How to find first n array items that match a condition without looping through entire array

Rather than putting a conditional and break inside a for loop, just add the extra length check in the for condition itself





const data = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14"],
isValid = n => !(n%2),
res = [],
max = 5;

for (let i = 0; i < data.length && res.length < max; i++) {
isValid(data[i]) && res.push(data[i]);
}

console.log(res)

In Kotlin, how can I take the first n elements of an array

The problem with your code that you create pairs with color constants which are Ints (allColours has type Array<Pair<Int, Int>>), but you expect Array<Pair<Color, Color>>. What you have to do is change type pegColours type and use take:

var pegColours: Array<Pair<Int, Int>> = allColours.take(3).toTypedArray() 

Also you have to call toTypedArray() cause Array.take returns List rather than Array. Or you can change pegColours type as following:

var pegColours: List<Pair<Int, Int>> = allColours.take(3)


Related Topics



Leave a reply



Submit