Skip to content

Instantly share code, notes, and snippets.

@kdipaolo
Created October 16, 2018 13:40
Show Gist options
  • Save kdipaolo/ad3a95baf269c45fade7a50cd2d3bd6c to your computer and use it in GitHub Desktop.
Save kdipaolo/ad3a95baf269c45fade7a50cd2d3bd6c to your computer and use it in GitHub Desktop.
Slice(), Splice(), Split()

Slice()

array.slice(start, stopAt);

The slice( ) method copies a given part of an array and returns that copied part as a new array. It doesn’t change the original array.

const array = [1,2,3,4,5,6]
const newArray = array.slice(0, 3) // [1, 2, 3]

Slice also works the same on strings:

const hello = "hello"
const he = test.slice(0, 2) // "he"

Splice()

array.splice(start index, number of elements);

The splice( ) method changes an array, by adding or removing elements from it.

If we don’t define the second parameter, every element starting from the given index will be removed from the array:

const array = [1,2,3,4,5]
array.splice(2);   // Removes 3,4,5
// array = [1, 2]

The second paramater tells splice when to stop removing elements from the array:

const array = [1,2,3,4,5]
const newArray = array.splice(2, 1);  // [3]
array = [1,2,4,5]

Split()

string.split(separator, limit);

The split( ) method is used for strings. It divides a string into substrings and returns them as an array. It takes 2 parameters, and both are optional.

const string = "12345"
const array = string.split("", 3) // ["1","2","3"]
const longerArray = string.split("") // ["1","2","3","4","5"]





Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment