2.7 KiB
2.7 KiB
id, title, challengeType, forumTopicId
id | title | challengeType | forumTopicId |
---|---|---|---|
587d78b2367417b2b2512b0e | Add Items to an Array with push() and unshift() | 1 | 301151 |
Description
Array.push()
and Array.unshift()
.
Both methods take one or more elements as parameters and add those elements to the array the method is being called on; the push()
method adds elements to the end of an array, and unshift()
adds elements to the beginning. Consider the following:
let twentyThree = 'XXIII';
let romanNumerals = ['XXI', 'XXII'];
romanNumerals.unshift('XIX', 'XX');
// now equals ['XIX', 'XX', 'XXI', 'XXII']
romanNumerals.push(twentyThree);
// now equals ['XIX', 'XX', 'XXI', 'XXII', 'XXIII']Notice that we can also pass variables, which allows us even greater flexibility in dynamically modifying our array's data.
Instructions
mixedNumbers
, which we are passing an array as an argument. Modify the function by using push()
and unshift()
to add 'I', 2, 'three'
to the beginning of the array and 7, 'VIII', 9
to the end so that the returned array contains representations of the numbers 1-9 in order.
Tests
tests:
- text: <code>mixedNumbers(["IV", 5, "six"])</code> should now return <code>["I", 2, "three", "IV", 5, "six", 7, "VIII", 9]</code>
testString: assert.deepEqual(mixedNumbers(['IV', 5, 'six']), ['I', 2, 'three', 'IV', 5, 'six', 7, 'VIII', 9]);
- text: The <code>mixedNumbers</code> function should utilize the <code>push()</code> method
testString: assert(mixedNumbers.toString().match(/\.push/));
- text: The <code>mixedNumbers</code> function should utilize the <code>unshift()</code> method
testString: assert(mixedNumbers.toString().match(/\.unshift/));
Challenge Seed
function mixedNumbers(arr) {
// change code below this line
// change code above this line
return arr;
}
// do not change code below this line
console.log(mixedNumbers(['IV', 5, 'six']));
Solution
function mixedNumbers(arr) {
// change code below this line
arr.push(7,'VIII',9);
arr.unshift('I',2,'three');
// change code above this line
return arr;
}