Skip to curriculum
Jump to the editor

4.13. Replace the middle three items of one array with another's

Easy
Topics

This question is in

4. Array utilities
10–15 min

A carousel shows a row of cards and highlights the three in the middle. A playlist editor swaps the middle of one list with the middle of another. Both need the same two steps: find where the "middle three" starts for an array of any length, and copy or replace exactly that range. The arithmetic is short, but an even length and a too-short array are where most first attempts go wrong.

Write middleThree(array) and replaceMiddle(target, source) in middle.js.

Signature

JAVASCRIPT
function middleThree(array)           // returns a new array of 3 items
function replaceMiddle(target, source) // returns a new array, as long as target
  • The middle three of an array with an odd length are centred: in 7 items, indexes 2, 3 and 4.
  • With an even length there is no exact centre, so the middle three lean toward the start: in 6 items, indexes 1, 2 and 3.
  • replaceMiddle returns a copy of target with its middle three items replaced by the middle three items of source.

Requirements

  1. middleThree returns the three centred items of an odd-length array.
  2. For an even length, it returns the three items that lean toward the start (in 4 items, indexes 0, 1 and 2).
  3. For exactly 3 items, it returns a copy of all three.
  4. An array with fewer than 3 items makes either function throw a RangeError.
  5. replaceMiddle replaces exactly the middle three items of target with the middle three of source, keeps every other item of target in place, and keeps target's length.
  6. The two arrays can have different lengths, odd or even.
  7. Both functions return new arrays, never change their inputs, and keep objects as they are.

Examples

JAVASCRIPT
middleThree([1, 2, 3, 4, 5, 6, 7]);   // [3, 4, 5]
middleThree([1, 2, 3, 4, 5, 6]);      // [2, 3, 4]: leans toward the start
middleThree([1, 2]);                  // throws RangeError
JAVASCRIPT
replaceMiddle(["a", "b", "c", "d", "e"], [1, 2, 3, 4, 5, 6, 7]);
// ["a", 3, 4, 5, "e"]
replaceMiddle([1, 2, 3, 4, 5, 6, 7, 8, 9], ["x", "y", "z"]);
// [1, 2, 3, "x", "y", "z", 7, 8, 9]

Environment

  • Plain JavaScript in a browser page; the tests call the globals middleThree and replaceMiddle from middle.js.
  • Any built-in may be used. Arrays have no holes.

Hints

  1. If the middle three start at index s in an array of length n, how many items are before them and how many after? What makes those two numbers as equal as possible?
  2. Which array method removes some items and inserts others in their place?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…