Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 28f2beb

Browse files
committedMay 19, 2025
Implement custom forEach methods for array manipulation
1 parent 32bfd41 commit 28f2beb

File tree

3 files changed

+69
-0
lines changed

3 files changed

+69
-0
lines changed
 

‎arrayqs_1/index.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
//Qs : There is an array which contains extra elements. You have to find the core element of array.
2+
3+
//Ans:
4+
5+
Array.prototype.newName = "waseem akram";
6+
7+
const newArr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
8+
// for (let v in newArr) {
9+
// console.log(v);
10+
// } //0
11+
// 1
12+
// 2
13+
// 3
14+
// 4
15+
// 5
16+
// 6
17+
// 7
18+
// 8
19+
// 9
20+
// newName
21+
22+
for (let v in newArr) {
23+
if (newArr.hasOwnProperty(v)) {
24+
console.log(v);
25+
}
26+
}
27+
//1,2,3,4,5,6,7,8,9,10

‎customForeach(1)

Whitespace-only changes.

‎customForeach/index.js

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
//Qs:implement custom forEach method
2+
//Ans:
3+
Array.prototype.customForEachOne = function (callback) {
4+
for (let i = 0; i < this.length; i++) {
5+
callback(this[i], i, this);
6+
}
7+
};
8+
9+
const numbers = [10, 20, 30];
10+
11+
numbers.customForEachOne(function (element, index, array) {
12+
console.log(`Element at index ${index}: ${element} In array: ${array}`);
13+
});
14+
// Output:
15+
// Element at index 0: 10 In array: 10,20,30
16+
// Element at index 1: 20 In array: 10,20,30
17+
// Element at index 2: 30 In array: 10,20,30\
18+
19+
Array.prototype.customForEachTwo = function (callback, thiscontext) {
20+
if (typeof callback !== "function") {
21+
throw new TypeError("callback is not a function");
22+
}
23+
for (let i = 0; i < this.length; i++) {
24+
callback.call(thiscontext, this[i], i, this);
25+
}
26+
};
27+
28+
const user = {
29+
name: "Ali",
30+
logColor: function (color, index) {
31+
console.log(`${this.name} likes color #${index + 1}: ${color}`);
32+
},
33+
};
34+
35+
const colors = ["purple", "orange", "cyan"];
36+
37+
colors.customForEachTwo(user.logColor, user); // Passing `user` as thiscontext
38+
// explaination:- .call() used for custom this context calling.
39+
// Output:
40+
// Ali likes color #1: purple
41+
// Ali likes color #2: orange
42+
// Ali likes color #3: cyan

0 commit comments

Comments
 (0)
Please sign in to comment.