It's often necessary to add pieces of data to arrays and extract elements from them. You may also want to divide strings and merge arrays or strings together. Fortunately, JavaScript provides methods that make it simple to perform such operations. In this topic, you will learn how to use these tools to splice, split, and concatenate sequences.
The splice method
You already know about slice(). It returns a partial copy of an array based on the given index values. splice() sounds similar, but don't let that confuse you — this method is a bit more complicated.
The first argument is the index at which the array will start changing, and it's the only one that's mandatory. The second argument is the number of elements that will be removed. Then you can specify the items that will be added in place of the deleted ones. It's possible to insert a larger or smaller number of elements.
splice() changes the contents of the original array.
Let's look at some examples:
let arr = ["one", "two", 3, "four", 5, 6, "seven", 8];
arr.splice(3, 2);
console.log(arr); // [ 'one', 'two', 3, 6, 'seven', 8 ]"four" is in index position 3, so it's the first element to be deleted. 5 is in index position 4 and is the second item to be removed.
Now let's insert strings to replace these two elements:
let arr = ["one", "two", 3, "four", 5, 6, "seven", 8];
arr.splice(3, 2, "Here's", "Johnny!");
console.log(arr); // [ 'one', 'two', 3, "Here's", 'Johnny!', 6, 'seven', 8 ]If you just want to insert items without deleting anything, pass 0 to the second parameter:
let arr = ["one", "two", 3, "four", 5, 6, "seven", 8];
arr.splice(1, 0, "Here's", "Johnny!");
console.log(arr); // [ 'one', "Here's", 'Johnny!', 'two', 3, 'four', 5, 6, 'seven', 8 ]When a single argument is provided, splice removes everything starting from the specified index:
let arr = ["one", "two", 3, "four", 5, 6, "seven", 8];
arr.splice(-3);
console.log(arr); // [ 'one', 'two', 3, 'four', 5 ]In addition to modifying the existing array, splice also returns an array containing the deleted elements:
let arr = ["one", "two", 3, "four", 5, 6, "seven", 8];
let newArr = arr.splice(-3);
console.log(arr); // [ 'one', 'two', 3, 'four', 5 ]
console.log(newArr); // [ 6, 'seven', 8 ]The split method
This method divides a string into pieces and places them in an array. The first parameter is a separator. split() searches for this pattern and divides the string in each place that it's found. The second parameter limits the number of elements included in the array. Both parameters are optional.
Consider the following example:
let str = "one two three";
let arr = str.split(" ");
console.log(arr); // [ 'one', 'two', 'three' ]Now let's limit ourselves to one element:
let arr = str.split(" ", 1);
console.log(arr); // [ 'one' ]Split returns an array containing a single string if you don't specify any parameters:
let arr = str.split();
console.log(arr); // [ 'one two three' ]To break up the string into an array of characters, use an empty separator:
let arr = str.split("", 7);
console.log(arr); // [ 'o', 'n', 'e', ' ', 't', 'w', 'o' ]You can pass a regular expression to the split method if you need greater flexibility when specifying separators.
The concat method
Okay, so we know how to splice and split. Now it's time to learn about merging arrays and strings with concat(). This method returns a new sequence rather than altering the existing ones.
One option is to call concat() on a previously created array and pass the arrays that we wish to combine it with as arguments:
let colors = ["red", "green", "blue"];
let numbers = [1, 2, 3, 4, 5];
let sounds = ["bark", "meow", "quack", "buzz"];
let arr = colors.concat(numbers, sounds);
console.log(arr);
// [ 'red', 'green', 'blue', 1, 2, 3, 4, 5, 'bark', 'meow', 'quack', 'buzz' ]However, there is another way to achieve the same result:
let colors = ["red", "green", "blue"];
let numbers = [1, 2, 3, 4, 5];
let sounds = ["bark", "meow", "quack", "buzz"];
let arr = [].concat(colors, numbers, sounds);
console.log(arr);
// [ 'red', 'green', 'blue', 1, 2, 3, 4, 5, 'bark', 'meow', 'quack', 'buzz' ]Here we've made an empty array and merged the three arrays with it.
You can also concatenate arrays with individual elements:
let colors = ["red", "green", "blue"];
let arr = ["white"].concat(colors, "black");
console.log(arr); // [ 'white', 'red', 'green', 'blue', 'black' ]Strings can be glued together with concat(), too:
let color1 = "red";
let color2 = "blue";
console.log(color1.concat(" ", color2)); // red blueAnd it's possible to join everything with an empty string as well:
console.log("".concat("The", " ", "Thing")); // The ThingAs you can see below, this method can also convert non-string arguments into strings before concatenation:
console.log("".concat(1, true)); // 1trueRead more on this topic in JavaScript Array Slicing Techniques on Hyperskill Blog.
Conclusion
You learned about three methods in this topic:
splice()removes and inserts data. It modifies the original array and returns an array containing any deleted items.split()divides a string and returns an array of the separated elements.concat()merges arrays or strings. It returns a new array or string containing the combined items.