Array Methods Interview Questions
Array.map()
The map()
method in JavaScript creates a new array populated with the results of calling a provided function on every element in the calling array. It doesn't modify the original array but returns a new modified array based on the callback function's logic.
const nums = [1, 2, 3, 4, 5];
const multiplayThree = nums.map((num, index, arr) => {
return num * 3 + index;
});
console.log(multiplayThree); // [ 3, 7, 11, 15, 19 ]
Array.filter()
The filter()
method creates a new array with all elements that pass the test implemented by the provided function. It returns a filtered array based on the condition specified in the callback function, where only elements that satisfy the condition are included.
const nums2 = [1, 2, 3, 4, 5];
const moreThanTwo = nums2.filter((num) => {
return num > 2;
});
console.log(moreThanTwo); // [ 3, 4, 5 ]
Array.reduce()
The reduce()
method executes a reducer function (that you provide) on each element of the array, resulting in a single output value. It's often used for aggregating data, such as calculating a sum, by iterating through the array and accumulating the results based on the logic in the callback function.
const nums3 = [1, 2, 3, 4, 5];
const sum = nums3.reduce((acc, curr, i, arr) => {
return acc + curr;
}, 0);
console.log(sum); // 15
Write our own Polyfill
Map Polyfill
This code snippet adds a custom implementation of the map()
method to the Array prototype. It mimics the functionality of the native map()
method by iterating through the array and applying a callback function to each element to create a new array with the modified values.
Array.prototype.myMap = function (cb) {
let temp = [];
for (let i = 0; i < this.length; i++) {
temp.push(cb(this[i], i, this));
}
return temp;
};
// Try our own map
const pollyNums = [20, 23, 45, 6];
const testMyMap = pollyNums.myMap((num, index, arr) => {
return num + index;
});
console.log(testMyMap);
Filter Polyfill
Similar to the Map Polyfill, this code adds a custom implementation of the filter()
method to the Array prototype. It iterates through the array and applies a callback function to each element, returning a new array containing only the elements that meet the specified condition in the callback.
Array.prototype.myFilter = function (cb) {
let temp = [];
for (let i = 0; i < this.length; i++) {
if (cb(this[i], i, this)) {
temp.push(this[i]);
}
}
return temp;
};
// Try our own filter
const prototypeNums2 = [1, 21, 31, 14, 51];
const moreThanTeen = prototypeNums2.myFilter((num) => {
return num > 10;
});
console.log(moreThanTeen);
Reduce Polyfill
This snippet introduces a custom implementation of the reduce()
method for arrays. It iterates through the array, applying a callback function that performs reduction or aggregation operations, similar to the native reduce()
method, and returns the final accumulated result.
Array.prototype.myReduce = function (cb, initialValue) {
var accumulator = initialValue;
for (let i = 0; i < this.length; i++) {
accumulator = accumulator ? cb(accumulator, this[i], i, this) : this[i];
}
return accumulator;
};
// Try our own reduce
const prototypeNums3 = [11, 21, 32, 41, 5];
const prototypeSum = prototypeNums3.reduce((acc, curr, i, arr) => {
return acc + curr;
}, 0);
console.log(prototypeSum); // 110
OUTPUT Based Questions π₯
Question 1: Return only names of the student in Capital letter
let students = [
{ name: "Sambit", rollNumber: 112, marks: 80 },
{ name: "Rakesh", rollNumber: 113, marks: 60 },
{ name: "Sourav", rollNumber: 14, marks: 58 },
{ name: "Soumya", rollNumber: 4, marks: 98 },
];
// By using tradition for loop
let studentName = [];
for (let i = 0; i < students.length; i++) {
studentName.push(students[i].name.toUpperCase());
}
console.log(studentName, ">> For Loop");
// By using ES6 Map
const nameUpperCase = students.map((ele) => {
return ele.name.toUpperCase();
});
console.log(nameUpperCase);
Question 2: Return only details of those who scored more than 60
const filterAboveAverageStudent = students.filter((stu) => stu.marks > 60);
console.log(filterAboveAverageStudent);
Question 3: Return only details of those who scored more than 60 and rollNumber greater than 15
const filterSpecificStudent = students.filter(
(stu) => stu.marks > 60 && stu.rollNumber > 15
);
console.log(filterSpecificStudent);
Question 4: Sum of marks of all students
const sumOfAllMArks = students.reduce((acc, curr) => {
return acc + curr.marks;
}, 0);
console.log(sumOfAllMArks);
Question 5: Return only names of students who scored more than 60
const studentsAboveAverage = students
.filter((stu) => stu.marks > 60)
.map((ele) => ele.name);
console.log(studentsAboveAverage);
Question 6: Return total mark for students with marks greater than 60 after 20 marks have been added to those who scored less than 60
const totalMarkAfterGrace = students
.map((stu) => {
if (stu.marks < 60) {
stu.marks += 20;
}
return stu;
})
.filter((stu) => stu.marks > 60)
.reduce((acc, curr) => acc + curr.marks, 0);
console.log(totalMarkAfterGrace);