Task for MAP method in
Javascript
Sure! Here are five tasks you can do using the map method in JavaScript:
1. Square each number in an array:
const numbers = [1, 2, 3, 4, 5];
const squaredNumbers = numbers.map(number => number * numb
er);
console.log(squaredNumbers); // Output: [1, 4, 9, 16, 25]
2. Convert an array of strings to uppercase:
const words = ['hello', 'world', 'javascript'];
const uppercasedWords = words.map(word => word.toUpperCase
());
console.log(uppercasedWords); // Output: ['HELLO', 'WORL
D', 'JAVASCRIPT']
3. Extract the 'name' property from an array of objects:
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Charlie' }
];
const userNames = users.map(user => user.name);
console.log(userNames); // Output: ['Alice', 'Bob', 'Charl
ie']
4. Append a suffix to each string in an array:
Task for MAP method in Javascript 1
const fileNames = ['report', 'summary', 'data'];
const updatedFileNames = fileNames.map(fileName => fileNam
e + '.txt');
console.log(updatedFileNames); // Output: ['report.txt',
'summary.txt', 'data.txt']
5. Increment each number in an array by 1:
const numbers = [1, 2, 3, 4, 5];
const incrementedNumbers = numbers.map(number => number +
1);
console.log(incrementedNumbers); // Output: [2, 3, 4, 5,
6]
These examples demonstrate various ways you can use the map method to
transform elements in an array.
Task for MAP method in Javascript 2