Array and String Methods

Fun with slice(), splice(), split(), join()!

Overview

split() – Turning Strings into arrays Using the split(separator) method on a string will quickly parse the string finding every instance of the separator character(s) that you identify, and where it finds them, “split” the string at that point and create an array element.

let str = 'This is a really cool thing';
let words = str.split(' ');
console.log(words);
  // prints out: [ 'This', 'is', 'a', 'really', 'cool', 'thing' ]

let iii = str.split('i');
console.log(iii);
  // prints out: [ 'Th', 's ', 's a really cool th', 'ng' ]

join() – Turning arrays into strings The join(char) array method will iterate an array and create a string by concatenating the value of each element in the array with the char that you specify.

let arr = ['this','was','fun']
console.log( arr.join() ); // commas will be the default
  // prints out: this,was,fun

console.log( arr.join('') ); // one long word
  // prints out: thiswasfun

console.log( arr.join('.') ); // millennial advertising
  // prints out: this.was.fun.

console.log( arr.join('-') ); // kebab case
  // prints out: this-was-fun

console.log( arr.join('_') ); // snake case
  // prints out: this_was_fun

slice() – Find elements within an array

let arr = ['a','b','c','d','e'];

// Find 2 elements starting at position 0
console.log( arr.slice(0,2) );
  // output: [ 'a', 'b' ]

// Find 2 elements starting at position 2
console.log( arr.slice(2,4) );
  // output: [ 'c', 'd' ]

// Find 1 elements starting at position 4
console.log( arr.slice(3,4) );
  // output: [ 'd' ]

// Find 1 elements starting at position 0
console.log( arr.slice(0,1) );
  // output: [ 'a' ]

// Find the last element
console.log( arr.slice(arr.length-1) );
  // output: [ 'e' ]

// 2 from the front to the end ...
console.log( arr.slice(2) );
  // output: [ 'c', 'd', 'e' ]

// 2 from the end to the front ...
console.log( arr.slice(-2) );
  // output: [ 'd', 'e' ]

splice() – replace parts of an array with new values

let arr = ['a','b','c','d','e'];

// At arr index 1, replace 0 elements with 99
// This will INSERT a new element into the array
arr.splice(1,0,99)
console.log(arr);
  // output: [ 'a', 99, 'b', 'c', 'd', 'e' ]

// At arr index 1, replace 1 element with nothing
// This will DELETE an array element at a particular index
arr.splice(1,1)
console.log(arr);
  // output: [ 'a', 'b', 'c', 'd', 'e' ]

// At arr index 2, replace 3 elements with 99
// This will shorten the array, but add a new value
arr.splice(2,3,99)
console.log(arr);
  // output: [ 'a', 'b', 99 ]

Reference and Resources