0
0
Javascriptprogramming~20 mins

Modifying arrays in Javascript - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
πŸŽ–οΈ
Array Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this code modifying an array with splice?
Consider the following JavaScript code that modifies an array using splice. What will be logged to the console?
Javascript
const arr = [10, 20, 30, 40, 50];
arr.splice(2, 2, 25, 35);
console.log(arr);
A[10, 20, 30, 40, 50]
B[25, 35, 50]
C[10, 20, 25, 35, 40, 50]
D[10, 20, 25, 35, 50]
Attempts:
2 left
πŸ’‘ Hint
Remember that splice(start, deleteCount, items...) removes deleteCount items starting at start, then inserts items.
❓ Predict Output
intermediate
2:00remaining
What is the output after using push and pop on an array?
Look at this code that modifies an array with push and pop. What will be the final output?
Javascript
const fruits = ['apple', 'banana'];
fruits.push('cherry');
const popped = fruits.pop();
console.log(fruits, popped);
A['apple', 'banana'] 'cherry'
B['apple', 'banana', 'cherry'] 'banana'
C['apple', 'banana'] 'banana'
D['apple', 'banana', 'cherry'] 'cherry'
Attempts:
2 left
πŸ’‘ Hint
push adds an item to the end, pop removes the last item and returns it.
πŸ”§ Debug
advanced
2:00remaining
Why does this code throw an error when modifying an array?
This code tries to modify an array but throws an error. What is the cause?
Javascript
const arr = Object.freeze([1, 2, 3]);
arr[0] = 10;
console.log(arr);
ASyntaxError: Unexpected token '='
BTypeError: Cannot assign to read only property '0' of object '[object Array]'
CReferenceError: arr is not defined
D[10, 2, 3]
Attempts:
2 left
πŸ’‘ Hint
Object.freeze makes an object immutable.
❓ Predict Output
advanced
2:00remaining
What is the output after using map and modifying the original array?
What will be logged after running this code that modifies an array inside a map callback?
Javascript
const nums = [1, 2, 3];
const result = nums.map((num, i, arr) => {
  arr[i] = num * 2;
  return num + 1;
});
console.log(result, nums);
A[2, 3, 4] [2, 4, 6]
B[2, 3, 4] [1, 2, 3]
C[1, 2, 3] [2, 4, 6]
D[1, 2, 3] [1, 2, 3]
Attempts:
2 left
πŸ’‘ Hint
The map callback modifies the original array while returning a new array.
🧠 Conceptual
expert
2:00remaining
Which option correctly removes all occurrences of a value from an array?
You want to remove all occurrences of the number 3 from an array. Which code snippet correctly does this without mutating the original array?
Aarr = arr.map(x => x === 3 ? null : x);
Barr.splice(arr.indexOf(3), 1);
Cconst filtered = arr.filter(x => x !== 3);
Darr.pop(3);
Attempts:
2 left
πŸ’‘ Hint
Filter creates a new array with only elements that pass the test.