Introduction
Hey, welcome back! Here is the sequel (Part 2) to the previous blog post. Are you ready for some more fun? 🔥
So here is the challenge!
Can you write the JavaScript Array methods listed below from scratch?
The Rules
- Don't use
prototype
. Instead, take the array as the first argument/parameter. - Don't use other native JavaScript methods to solve the problems
- Feel free to use the latest ECMAScript standards such as the
rest
operator,spread
operator, default values, etc... - Pay attention to understand if a method modifies the original array or returns a new array! Or if anything is returned at all.
- Don't look up the solutions until you really tried!
Array methods
The Solutions
forEach
function forEach(array, callback) {
for(let i=0; i<array.length; i++) {
callback(array[i], i, array)
}
}
map
function map(array, callback) {
const result = []
for(let i=0; i<array.length; i++) {
result.push(callback(array[i], i, array))
}
return result
}
filter
function filter(array, callback) {
const result = []
for(let i=0; i<array.length; i++) {
if(callback(array[i], i, array)) {
result.push(array[i])
}
}
return result
}
reduce
// here is my attempt, can you do better?
function reduce(array, callback, initialValue) {
let accumulator = initialValue || array[0]
if(initialValue === 0) {
accumulator = 0
}
for(let i=0; i<array.length; i++) {
if(initialValue === undefined && i === 0) {
continue
}
accumulator = callback(accumulator, array[i], i, array)
}
return accumulator
}
find
function find(array, callback) {
for(let i=0; i<array.length; i++) {
if(callback(array[i], i, array)) {
return array[i]
}
}
}
findIndex
function findIndex(array, callback) {
for(let i=0; i<array.length; i++) {
if(callback(array[i], i, array)) {
return i
}
}
return -1
}
some
function some(array, callback) {
let flag = false
for(let i=0; i<array.length; i++) {
if(callback(array[i], i, array)) {
flag = true
}
}
return flag
}
every
function every(array, callback) {
let flag = true
for(let i=0; i<array.length; i++) {
if(!callback(array[i], i, array)) {
flag = false
}
}
return flag
}
Parting words 👋
I hope you enjoyed the challenge as much as I did! 🎉. Feel free to provide any feedback including 🐛's. I would also love to see your codes, feel free to post them as comments. Thank you and adios.