From what I understood from your answers what you need is to filter the array:

Copyconst filteredArray = array.filter(element => {
    if (yourConditionIsTrue) { // if this element should be in the filteredArray
        return true;
    } else {
        return false
    }
});

Which can be done in one line:

Copyconst filteredArray = array.filter(element => conditionIsTrue);

This way your array remains untouched and you get a new array (filteredArray) only with the elements you need, but you don't mess up with the array you are iterating.

Answer from A. Llorente on Stack Overflow
🌐
TutorialsPoint
tutorialspoint.com › home › typescript › typescript array slice
TypeScript Array Slice
December 18, 2016 - Returns the extracted array based on the passed parameters. var arr = ["orange", "mango", "banana", "sugar", "tea"]; console.log("arr.slice( 1, 2) : " + arr.slice( 1, 2) ); console.log("arr.slice( 1, 3) : " + arr.slice( 1, 3) );
🌐
GeeksforGeeks
geeksforgeeks.org › typescript › typescript-array-slice-method
TypeScript Array slice() Method - GeeksforGeeks
August 8, 2024 - Example 2: In this example we defines a string array arr, then uses the slice() method to extract portions of the array into val.
🌐
Educative
educative.io › answers › what-is-arrayslice-in-typescript
What is array.slice() in TypeScript?
TypeScript is a superset of JavaScript. Wherever JavaScript runs, TypeScript runs, too. We can use the slice() method in TypeScript. This method is used to extract a certain section or parts of the elements of an array.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › slice
Array.prototype.slice() - JavaScript | MDN
In this example, slice(1, -1) starts extracting from index 1 and goes up to, but does not include, the element at index -1 (which is the last element). This results in a new array with ['Banana', 'Orange', 'Mango']. The slice method always excludes the element at the final index specified, ...
🌐
HowToDoInJava
howtodoinjava.com › home › typescript › typescript array slice()
TypeScript Array slice() with Examples
August 29, 2023 - For object types, slice() will copy the reference of the objects to the new array. So, any change in the objects will be visible in both arrays. In the following example, we are modifying the age of employee2.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › TypedArray › slice
TypedArray.prototype.slice() - JavaScript | MDN
This method is not generic and can only be called on typed array instances. ... const bytes = new Uint8Array([1, 2, 3]); bytes.slice(1); // Uint8Array [ 2, 3 ] bytes.slice(2); // Uint8Array [ 3 ] bytes.slice(-2); // Uint8Array [ 2, 3 ] bytes.slice(0, 1); // Uint8Array [ 1 ]
Find elsewhere
Top answer
1 of 2
32

Yes, you can use conditional type inference on the function type, in a way very similar to how the Parameters utility type is implemented:

type ParametersExceptFirst<F> = 
   F extends (arg0: any, ...rest: infer R) => any ? R : never;

compare to

// from lib.es5.d.ts
type Parameters<T extends (...args: any) => any> = 
  T extends (...args: infer P) => any ? P : never;

and verify that it works:

declare function foo(x: string, y: number, z: boolean): Date;
type FooParamsExceptFirst = ParametersExceptFirst<typeof foo>;
// type FooParamsExceptFirst = [y: number, z: boolean]
declare function foo(x: string, y: number, z: boolean): Date;

Playground link to code


UPDATE: arbitrary slicing of tuples with numeric literals is possible, but not pretty and has caveats. First let's write TupleSplit<T, N> which takes a tuple T and a numeric literal type N, and splits the tuple T at index N, returning two pieces: the first piece is the first N elements of T, and the second piece is everything after that. (If N is more than the length of T then the first piece is all of T and the second piece is empty):

type TupleSplit<T, N extends number, O extends readonly any[] = readonly []> =
    O['length'] extends N ? [O, T] : T extends readonly [infer F, ...infer R] ?
    TupleSplit<readonly [...R], N, readonly [...O, F]> : [O, T]

This works via recursive conditional types on variadic tuples and is therefore more computationally intensive than the relatively simple ParametersExceptFirst implementation above. If you try this on long tuples (lengths more than 25 or so) you can expect to see recursion errors. If you try this on ill-behaved types like non-fixed-length tuples or unions of things, you might get weird results. It's fragile; be careful with it.

Let's verify that it works:

type Test = TupleSplit<readonly ["a", "b", "c", "d", "e"], 3>
// type Test = [readonly ["a", "b", "c"], readonly ["d", "e"]]

Looks good.


Now we can use TupleSplit<T, N> to implement TakeFirst<T, N>, returning just the first N elements of T, and SkipFirst<T, N>, which skips the first N elements of T:

type TakeFirst<T extends readonly any[], N extends number> =
    TupleSplit<T, N>[0];

type SkipFirst<T extends readonly any[], N extends number> =
    TupleSplit<T, N>[1];

And finally TupleSlice<T, S, E> produces the slice of tuple T from start position S to end position E (remember, slices are inclusive of the start index, and exclusive of the end index) by taking the first E elements of T and skipping the first S elements of the result:

type TupleSlice<T extends readonly any[], S extends number, E extends number> =
    SkipFirst<TakeFirst<T, E>, S>

To demonstrate that this more or less represents what array slice() does, let's write a function and test it:

function slice<T extends readonly any[], S extends number, E extends number>(
    arr: readonly [...T], start: S, end: E
) {
    return arr.slice(start, end) as readonly any[] as TupleSlice<T, S, E>;
}

const tuple = ["a", "b", "c", "d", "e"] as const
// const tuple: readonly ["a", "b", "c", "d", "e"]

const ret0 = slice(tuple, 2, 4);
// const ret0: readonly ["c", "d"]
console.log(ret0); // ["c", "d"]

const ret1 = slice(tuple, 0, 9);
// const ret1: readonly ["a", "b", "c", "d", "e"]
console.log(ret1); // ["a", "b", "c", "d", "e"];

const ret2 = slice(tuple, 5, 3);
// const ret2: readonly []
console.log(ret2); // [];

This looks good; the returned arrays from slice() have types that accurately represent their values.

Of course, there are many caveats; if you pass negative or non-whole numbers to slice() for S and E, then TupleSlice<T, S, E> is very likely not to correspond to what actually happens with array slices: negative "from end" behavior is possibly implementable but it would be even uglier; non-whole numbers or even just number have not been tested but I expect recursion warnings and other things that go bump in the night. Be warned!

Playground link to code

2 of 2
0

@jcalz accepted solution here has a limitation: it drops tuple labels:

type OriginalTupleSplit = TupleSplit<[a: 1, b: 2, c: 3, d: 4, e: 5], 2> 
// [[1, 2], [c: 3, d: 4, e: 5]]

Below is a modified version that doesn't do that:

type TupleSplitHead<T extends any[], N extends number> = T['length'] extends N
  ? T
  : T extends [...infer R, any]
  ? TupleSplitHead<R, N>
  : never

type TupleSplitTail<T, N extends number, O extends any[] = []> = O['length'] extends N
  ? T
  : T extends [infer F, ...infer R]
  ? TupleSplitTail<[...R], N, [...O, F]>
  : never

type TupleSplit<T extends any[], N extends number> = [TupleSplitHead<T, N>, TupleSplitTail<T, N>]

type ModifiedTupleSplit = TupleSplit<[a: 1, b: 2, c: 3, d: 4, e: 5], 2>
// [[a: 1, b: 2], [c: 3, d: 4, e: 5]]

code

This is less performant than @jcalz's solution - as it iterates the array twice, but it keeps the labels.

🌐
Built In
builtin.com › software-engineering-perspectives › array-slice-javascript
3 Ways to Use Array Slice in JavaScript | Built In
Using the shift and pop method, you can remove an element at the front and end of the array respectively. The splice() method can also be used remove elements at a specific index, but it modifies the original array.
🌐
Fjolt
fjolt.com › article › javascript-slice
Javascript Array Slice Method
If a value greater than the array length is used, slice only continues to the end of the array. If a negative value is used, it indicates an offset from the end of an array. For example, (2, -1) will go 2 from the start, and -1 from the end of an array:
🌐
W3Schools
w3schools.com › jsref › jsref_slice_array.asp
JavaScript Array slice() Method
Array[ ] Array( ) at() concat() constructor copyWithin() entries() every() fill() filter() find() findIndex() findLast() findLastIndex() flat() flatMap() forEach() from() includes() indexOf() isArray() join() keys() lastIndexOf() length map() of() pop() prototype push() reduce() reduceRight() rest (...) reverse() shift() slice() some() sort() splice() spread (...) toReversed() toSorted() toSpliced() toString() unshift() values() valueOf() with() JS Boolean
Top answer
1 of 4
2

.splice() returns the deleted elements, but if you use it in a separate line:

Copyvar arr = ['Apple', 'Orange', 'Plums', 'Grapes'];

arr.splice(arr.indexOf('Orange'), 1);

console.log(arr);
Run code snippetEdit code snippet Hide Results Copy to answer Expand

Or you can use .slice() like this: (it's a bit long)

Copyvar arr = ['Apple', 'Orange', 'Plums', 'Grapes'];

//This slices from the start up to "Orange", then concatenates from after "Orange" to the end of the array
console.log(arr.slice(0, arr.indexOf('Orange')).concat(arr.slice( arr.indexOf('Orange') + 1, arr.length)));
Run code snippetEdit code snippet Hide Results Copy to answer Expand

2 of 4
2

So slice does not work the same as splice

Array.slice takes two parameter, start and end. So in your first function you are giving the start index of Orange and the end index of 1 which I think doesn't make sense because the slice is getting items within a range, so there are no items between that range.

So if you look at the code snippet I have the index of Orange and then the index one up because the slice is inclusive so you in your example Orange is at the 1 index and then you are doing 1 as the end index. So I am pulling everything between index 1 and index 2, which is Orange.

Copylet newArray;
let mutatedArray;

function removeOneFruit() {
  newArray=['Apple', 'Orange', 'Plums', 'Grapes'];
  console.log("Before slicing: "+newArray);
  mutatedArray=newArray.slice(newArray.indexOf('Orange'), newArray.indexOf('Orange')+1);
  console.log("After slicing: "+mutatedArray);
}

removeOneFruit()
Run code snippetEdit code snippet Hide Results Copy to answer Expand

Your second function you are using splice which is used to remove items from an array. Array.splice takes an index and the amount of items you want to remove at that index. So all you are doing is creating a new array with the item that you remove. If you wanted return an array with everything but Orange. Then you would run splice, which would remove Orange, and then point the mutatedArray to the new value of newArray.

Copylet newArray;
let mutatedArray;

function removeOneFruit() {
  newArray=['Apple', 'Orange', 'Plums', 'Grapes'];
  console.log("Before splicing: "+newArray);
  newArray.splice(newArray.indexOf('Orange'),1);
  mutatedArray= newArray;
  console.log("After splicing: "+mutatedArray);
}

removeOneFruit()
Run code snippetEdit code snippet Hide Results Copy to answer Expand

🌐
Python Examples
pythonexamples.org › typescript › Array › slice
TypeScript Array slice() - Syntax & Examples
Create an array arr with numeric values [1, 2, 3, 4, 5]. Use slice(-3) to extract the last three elements of the array.
🌐
TypeScript
typescriptlang.org › docs › handbook › 2 › everyday-types.html
TypeScript: Documentation - Everyday Types
For example, TypeScript knows that only a string value will have a typeof value "string": ... Notice that in the else branch, we don’t need to do anything special - if x wasn’t a string[], then it must have been a string. Sometimes you’ll have a union where all the members have something in common. For example, both arrays and strings have a slice method.
🌐
Java Guides
javaguides.net › 2025 › 01 › typescript-array-slice.html
TypeScript Array slice()
January 4, 2025 - In this example, we use slice() to extract elements from the start index to the end of the array.
🌐
Mimo
mimo.org › glossary › javascript › array-slice
JavaScript Array slice() Method: Syntax, Usage, and Examples
For large arrays, performance can degrade slightly, especially if called repeatedly in render cycles. When performance is a concern, benchmark different cloning or filtering strategies. ... Avoid modifying source data directly when copying or extracting elements. ... If you only need a subset or copy, use slice() instead of splice() which mutates the array.
🌐
Ramesh Fadatare
rameshfadatare.com › home › typescript array slice()
TypeScript Array slice()
July 9, 2024 - In this chapter, we will explore the slice() method for arrays in TypeScript. This method is a built-in function that returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array.