The Okafor family wants next week’s meal plan to start from last week’s, with a few changes. Two dinners swap places, Friday’s takeout pizza goes, and a new recipe, egusi soup, comes in. Each of those changes edits an array by taking part of it, removing an item, inserting one, or putting items in a new order.
In this lesson, you’ll use .slice(), .splice(), .concat(), and .reverse() on the family’s flat lists of dinners, groceries, and meals. You’ll be able to predict what each call returns and what the original array holds afterward. The methods differ most in that second part, so you’ll start with .slice(), which never changes its array.
Copy a Range With .slice()
Ngozi wants to see the weekday dinners apart from the weekend ones, without losing the full week. The .slice() method puts the items from a range of an array into a new array. You give it a start position and an end position, and it copies every item from the start up to but not including the end.
Create a file named dinners.js with last week’s seven dinners, Monday first:
dinners.js
const dinners = [
"jollof rice",
"pepper soup",
"spaghetti and meatballs",
"bean tacos",
"takeout pizza",
"veggie stir-fry",
"chicken curry",
];
const weekdays = dinners.slice(0, 5);
const weekend = dinners.slice(-2);
console.log("Weekdays:", weekdays);
console.log("Weekend:", weekend);
console.log("All week:", dinners);
Run it with node dinners.js:
$ node dinners.js
Weekdays: [
'jollof rice',
'pepper soup',
'spaghetti and meatballs',
'bean tacos',
'takeout pizza'
]
Weekend: [ 'veggie stir-fry', 'chicken curry' ]
All week: [
'jollof rice',
'pepper soup',
'spaghetti and meatballs',
'bean tacos',
'takeout pizza',
'veggie stir-fry',
'chicken curry'
]
The call dinners.slice(0, 5) copies the items at positions 0 to 4, Monday to Friday. The end position, 5, is Saturday’s place, and it’s left out. The end position marks the first item you don’t get, so 5 - 0 gives you five dinners.
The call dinners.slice(-2) uses a negative position, which counts back from the end of the array: -1 refers to the last item, and -2 refers to the one before it. With no end position, .slice() copies all the way to the end, so you get Saturday and Sunday.
Look twice at the last line of output. After two slices, dinners still holds all seven dinners. The .slice() method builds a new array of the selected items and leaves the one you call it on as it was. For flat lists of strings like these, that’s the whole story. Arrays that hold objects come up later, and that’s all you need about them for now.
Change the Array With .splice()
Copying is fine for looking at the week, but next week’s plan has to take one dinner out and put another in. The .splice() method does that. It edits the array you call it on, in place, as .sort() does when it rearranges an array instead of building a new one.
Remove and Insert by Position
The call .splice(start, count) removes count items, starting at position start, and returns them in a new array. Friday’s takeout pizza sits at position 4. Replace the lines after the array in dinners.js to remove that one dinner:
dinners.js
const dinners = [
"jollof rice",
"pepper soup",
"spaghetti and meatballs",
"bean tacos",
"takeout pizza",
"veggie stir-fry",
"chicken curry",
];
const removed = dinners.splice(4, 1);
console.log("Removed:", removed);
console.log("Dinners:", dinners);
Before you run it, write down what you expect each of the two lines to log. Then run node dinners.js and open the box to compare:
$ node dinners.js
Removed: [ 'takeout pizza' ]
Dinners: [
'jollof rice',
'pepper soup',
'spaghetti and meatballs',
'bean tacos',
'veggie stir-fry',
'chicken curry'
]
Even when .splice() removes one item, it returns an array, so you get [ 'takeout pizza' ] instead of the bare string. And dinners now has six dinners: the array keeps what’s left, and the return value is what’s gone.
To tell the two apart, remember that .slice() copies a range and leaves the original alone. .splice() changes the original and returns what it took out. The names differ by one letter, so when you meet either one in code, ask yourself: Does this change the original?
To put that question to both methods at once, move the sliders below. They set a start that both calls share, an end for .slice(), and a count for .splice(), and each call runs on its own fresh copy of the seven dinners. Try a negative start too, which counts back from the end:
However you set the sliders, dinners still holds seven dinners after .slice(), and it loses exactly the dinners that .splice() returns. With the first setting, a start of 2, an end of 5, and a count of 3, both calls even return the same three dinners, and only .splice() takes them out of the array.
After the count, .splice() takes any number of items to insert at start. With a count of 0, nothing is removed, so the call only inserts. With a count of 1 and one new item, the call swaps one dinner for another. That second form is what the family needs to put egusi soup in place of the takeout:
dinners.js
const dinners = [
"jollof rice",
"pepper soup",
"spaghetti and meatballs",
"bean tacos",
"takeout pizza",
"veggie stir-fry",
"chicken curry",
];
const removed = dinners.splice(4, 1, "egusi soup");
console.log("Removed:", removed);
console.log("Dinners:", dinners);
Run it, and Friday has a home-cooked dinner:
$ node dinners.js
Removed: [ 'takeout pizza' ]
Dinners: [
'jollof rice',
'pepper soup',
'spaghetti and meatballs',
'bean tacos',
'egusi soup',
'veggie stir-fry',
'chicken curry'
]
The week still has seven dinners because one went out and one came in at the same position. Try a count of 0 instead of 1, and you’ll see eight dinners, with the takeout pushed to Saturday’s place. Like .slice(), .splice() reads a negative start as counting back from the end.
If the start position, the count, and the items to insert in a .splice() call still blur together, ask for a few calls to work through:
Remove an Item by Value
Often you know which item should go, but not where it is. Ada has already bought the plantains, so they can come off the grocery list. The .indexOf() method gives you an item’s position, or -1 when the array doesn’t have it, and .splice() can then remove the item at that position.
Create groceries.js:
groceries.js
const groceries = [
"rice",
"tomatoes",
"scotch bonnets",
"plantains",
"onions",
];
const index = groceries.indexOf("plantains");
if (index !== -1) {
groceries.splice(index, 1);
}
console.log(groceries);
Run it, and the plantains are gone:
$ node groceries.js
[ 'rice', 'tomatoes', 'scotch bonnets', 'onions' ]
The if statement is there for the day the item isn’t on the list. For a missing item, .indexOf() returns -1. Without the guard, .splice(-1, 1) reads that as “the last item,” so "onions" would disappear without any error. To test the guard, change only the argument in groceries.indexOf("plantains") to "yams" and leave the array as it is. When you run the script again, all five groceries stay.
Combine and Reorder Arrays
The last two tweaks are joining two lists and flipping the order of one. One of the methods for them builds a new array, and the other changes its array in place.
Adding egusi soup means buying its ingredients too. Your first idea might be .push(), which you used in Lists With Arrays to add an item to the end of an array. Try it with a second list:
groceries.js
const groceries = ["rice", "tomatoes", "onions"];
const egusiItems = ["egusi seeds", "spinach", "palm oil"];
groceries.push(egusiItems);
console.log(groceries);
Run it, and look at the last item:
$ node groceries.js
[
'rice',
'tomatoes',
'onions',
[ 'egusi seeds', 'spinach', 'palm oil' ]
]
The .push() method added the whole egusiItems array as one item, so the list now has four items, and the fourth one is a list. The .concat() method joins the items of both arrays into a new array instead and leaves both originals as they were:
groceries.js
const groceries = ["rice", "tomatoes", "onions"];
const egusiItems = ["egusi seeds", "spinach", "palm oil"];
const shoppingList = groceries.concat(egusiItems);
console.log("Shopping list:", shoppingList);
console.log("Groceries:", groceries);
Run it, and you get a flat list of six items, while groceries still has three:
$ node groceries.js
Shopping list: [ 'rice', 'tomatoes', 'onions', 'egusi seeds', 'spinach', 'palm oil' ]
Groceries: [ 'rice', 'tomatoes', 'onions' ]
Reordering is the other tweak. On Mondays, Ngozi has an evening class, so she wants to cook the jollof rice at lunchtime and leave the leftover rice for dinner. Monday’s meals array holds lunch, then dinner, and .reverse() flips that order:
monday.js
const meals = ["leftover rice", "jollof rice"];
meals.reverse();
console.log(meals);
Run it, and lunch and dinner have swapped:
$ node monday.js
[ 'jollof rice', 'leftover rice' ]
Like .sort(), .reverse() works in place: it rearranges the array you call it on and hands back that same array, not a reversed copy. Here that’s what Ngozi wants. When you need the original order too, .reverse() is the wrong tool.
Check Your Understanding
Try one small edit on your own. Chidi suggests cooking last week’s weekday dinners in reverse order, starting with Friday’s dinner on Monday. Write reversed.js with the seven dinners from dinners.js. Then build a new array of the five weekday dinners in reverse order, and print it next to dinners. Before you run it, decide which method should go first, so that dinners still holds all seven dinners, Monday first.
One way to write it:
reversed.js
const dinners = [
"jollof rice",
"pepper soup",
"spaghetti and meatballs",
"bean tacos",
"takeout pizza",
"veggie stir-fry",
"chicken curry",
];
const weekdaysReversed = dinners.slice(0, 5).reverse();
console.log("Reversed:", weekdaysReversed);
console.log("Dinners:", dinners);
Run it with node reversed.js, and only the new array is reversed:
$ node reversed.js
Reversed: [
'takeout pizza',
'bean tacos',
'spaghetti and meatballs',
'pepper soup',
'jollof rice'
]
Dinners: [
'jollof rice',
'pepper soup',
'spaghetti and meatballs',
'bean tacos',
'takeout pizza',
'veggie stir-fry',
'chicken curry'
]
The order of the two calls is what keeps dinners safe. .slice(0, 5) builds a new array of the weekday dinners, and .reverse() flips that new array in place. Written the other way around, dinners.reverse().slice(0, 5) would flip dinners itself first.
You can now cut, insert, combine, and reorder arrays, and for each method you know whether it changes the original. The family’s real plan, though, is a whole week of day records, and next week’s plan has to start from those records without changing the original. In the next lesson, Trace Two Names to One Object, you’ll ask that same question about last week’s plan.