Introduction
In this lab, we will explore how to pull values from an array at specific indexes using JavaScript. We will be using the pullAtIndex() function, which mutates the original array to filter out the values at the specified indexes and returns the removed elements. By the end of this lab, you will have a solid understanding of how to manipulate arrays in JavaScript.
How to Pull Values From Array at Index
To pull out specific values from an array at certain indexes, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use
Array.prototype.filter()andArray.prototype.includes()to filter out the values that are not needed and store them in a new array calledremoved. - Set
Array.prototype.lengthto0to mutate the original array by resetting its length. - Use
Array.prototype.push()to re-populate the original array with only the pulled values. - Use
Array.prototype.push()to keep track of the removed values. - The function
pullAtIndextakes two arguments: the original array and an array of indexes to pull out. - The function returns an array of removed values.
Example usage:
const pullAtIndex = (arr, pullArr) => {
let removed = [];
let pulled = arr
.map((v, i) => (pullArr.includes(i) ? removed.push(v) : v))
.filter((v, i) => !pullArr.includes(i));
arr.length = 0;
pulled.forEach((v) => arr.push(v));
return removed;
};
let myArray = ["a", "b", "c", "d"];
let pulled = pullAtIndex(myArray, [1, 3]);
// myArray = [ 'a', 'c' ] , pulled = [ 'b', 'd' ]
Summary
Congratulations! You have completed the Pull Values From Array at Index lab. You can practice more labs in LabEx to improve your skills.