1.Calculate the sum of all the values in an array
const arr= [1,4,5,7];
const arrSum = arr.reduce((a,b)=>a+b);
// valSum -- 17
2.Generating array from a function arguments
function generateArray() {
return Array.from(arguments);
}
f(1,2,4))
//result -- [1,2,4]
3.Sorting the value of an array in ascending order.
const sortArrayValues = (values) => {
if(!Array.isArray(values)){
return null
}
return values.sort((a,b)=>a-b);
}
4.Reverse the values of an array
const fruits= ['Banana','Orange','Melon','Grape'];
const reverseFruits = fruits.reverse();
//result ['Grape','Melon','Orange','Banana'];
5.Removing the duplicates in an array
let fruits = ['banana','mango','apple','sugarcane','mango','apple']
let uniqueFruits = Array.from(new Set(fruits));
// uniqueFruits -- [ 'banana', 'manago', 'apple', 'sugarcane' ]
6.Emptying an array.
let fruits = [3,'mango',6,9,'mango','apple']
fruits.length = 0;
7.Convert an array to an Object.
const arrayVal= ['Tokyo', 'Belfast','Birmigham', 'Lagos']
const fruitsObj = {...arrayVal};
8.Merging multiple arrays into one.
let fruits = ['banana','manago','apple'];
let meat = ["Poultry","beef","fish"]
let vegetables = ["Potato","tomato","cucumber"];
let food = [...fruits,...meat,...vegetables];
// food -- ['banana', 'manago','apple', 'sugarcane','manago', 'apple','Poultry', 'beef','fish', 'Potato','tomato', 'cucumber'
9.Replace a specific value in an array
var fruits2 = ['apple', 'sugarcane', 'manago'];
fruits2.splice(0,2,"potato","tomato");
// fruits2 ['potato', 'tomato', 'apple', 'sugarcane', 'manago']
10.Mapping array from objects without maps
const friends = [
{name:"John", age:22},
{name:"Peter", age:23},
{name:"bimbo",age:34},
{name:"mark",age:45},
{name:"Esther",age:21},
{name:"Monica",age:19}
];
let friendNames = Array.from(friends,({name})=>name);
// friendNames --['John', 'Peter', 'bimbo', 'mark', 'Esther', 'Monica' ]
11.Filling an array with data
let newArray = new Array(8).fill("3");
// result -- ['3', '3', '3', '3','3', '3', '3', '3']
12.Merging only duplicates values in two arrays
let arrOne = [0,3,4,7,8,8];
let arrTwo = [1,2,3,4,8,6];
const duplicatedValue = [...new Set(arrOne)].filter(item=>arrTwo.includes(item));
// duplicatedValue -- [ 3, 4, 8]
13.Remove falsy values in an array.
const mixedValues = [undefined,"blue",0,"",NaN,true,,"white",false];
const filteredArray = mixedArray.filter(Boolean);
//result [ 'blue', true, 'white' ]
Top comments (0)