Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save Tellisense/ba0641d74fc04a37c41dfbd74e718298 to your computer and use it in GitHub Desktop.
Save Tellisense/ba0641d74fc04a37c41dfbd74e718298 to your computer and use it in GitHub Desktop.
Creating our own advanced Array methods: forEach, map, filter, reduce, every and some, using native javascript code, so that we can understand them better.
//forEach
Array.prototype.myforEach = function(cb) {
for (let i = 0; i < this.length; i++){
cb(this[i], i, this);
}
return undefined;
};
//map
Array.prototype.myMap = function(cb) {
let newArr = [];
for (let i = 0; i < this.length; i++){
newArr.push(cb(this[i], i, this));
}
return newArr;
};
//filter
Array.prototype.myFilter = function(cb) {
let newArr = [];
for (let i = 0; i < this.length; i++) {
if (cb(this[i], i, this)){
newArr.push(this[i]);
}
}
return newArr;
};
//some
Array.prototype.mySome = function(cb) {
for (let i = 0; i < this.length; i++) {
if (cb(this[i], i, this)){
return true;
}
};
return false;
};
//every
Array.prototype.myEvery = function(cb) {
for (let i = 0; i < this.length; i++) {
if (!cb(this[i], i, this)){
return false;
}
};
return true;
};
//reduce
Array.prototype.myReduce = function(cb, initialVal) {
var accumulator = (initialVal === undefined) ? undefined : initialVal;
for (var i = 0; i < this.length; i++) {
if (accumulator !== undefined){
accumulator = cb.call(undefined, accumulator, this[i], i, this);
} else {
accumulator = this[i];
}
}
return accumulator;
};
@Tellisense
Copy link
Author

thanks Dmitry!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment