DEV Community

Ruxin Qu
Ruxin Qu

Posted on

JS array methods

  • array.split() turns a string into an array and returns the array
const text = "I love doing web development";
const myArray = text.split(" ");
//output: [ 'I', 'love', 'doing', 'web', 'development' ]
const newArray = text.split("");
//output: [
  'I', ' ', 'l', 'o', 'v', 'e',
  ' ', 'd', 'o', 'i', 'n', 'g',
  ' ', 'w', 'e', 'b', ' ', 'd',
  'e', 'v', 'e', 'l', 'o', 'p',
  'm', 'e', 'n', 't'
]
Enter fullscreen mode Exit fullscreen mode
  • array.slice() take a cut of the original array and return the cut part
const myArr = ['apple','pear','strawberry']
const cut = myArr.slice(0,1)
//output: 'apple' it slice between the zero index and the first index
Enter fullscreen mode Exit fullscreen mode
  • string.slice() can also be used on a string. Note: .slice doesn't change the original string or array. The cut includes the start and excludes the end
const myText="I have a golden retriever"
const cut = myText.slice(3,5)
//output: 'av' 
Enter fullscreen mode Exit fullscreen mode
  • array.splice() can be used to add/remove one or multiple elements in an array. Note: it does change the original array

for removing element(s):

const array = ["I", "love", "doing", "web", "development"];
console.log(array.splice(0, 2));
//output: [ 'I', 'love' ]
console.log(array);
//output: [ 'doing', 'web', 'development' ]
Enter fullscreen mode Exit fullscreen mode

for adding element(s):

array.splice(0, 2, "hello");
console.log(array);
//output: [ 'hello', 'doing', 'web', 'development' ] it removes the elements between index 0 and 2 and adds the provided element to the 0th index
array.splice(5, 0, "very", "much", "!");
console.log(array);
//output: [ 'I', 'love', 'doing', 'web', 'development', 'very', 'much', '!' ] it found the 5th index and remove 0 element and add the provided elements to the 5th index
Enter fullscreen mode Exit fullscreen mode

Top comments (0)