101 0 0 0
Last Updated : 2021-01-18 12:38:42
Here are some of the most important and userd array functions and methods in Javascript.
Here are a list of the most important array methods in javascript.
Here is a samle of an array in Javascript
const names = ['Mohammed', 'Ahmed', 'Hassan', 'Nehad', 25, 'Ahmed'];
//ProtoType for this function , This will return the index if value is found or -1 other wise.
// You can check if element is found or not using if(index !== -1)
const index = Array.indexOf('value', startingPosition);
//To find the first index for Ahmed in this array
const index = data.indexOf('Ahmed')
//To find the last index for Ahmed
const index = data.lastIndexOf('Ahmed');
//---------------------------------->Array
const data = [
{name: "Ahmed"},
{name: "Ali"},
{name: "Hassan"}
]
//---------------------------------->ProtoType
data.find((element, index, fullArray)=>{
return element.innerIndex == 'value'
});
//---------------------------------->Example, Search for Ahmed
const AhmedObj = data.find((element, index, fullArray)=>{
return element.name == 'Ahmed';
});
console.log(AhmedObj);
//---------------------------------->Example, Search for Ahmed index
const AhmedIndex = data.findIndex((element, index, fullArray)=>{
return element.name == 'Ahmed';
});
console.log(AhmedIndex);
//----------------------------------> Important note
//These find function will return the object itself, So if you changed the name in the returned object, it will be changed in the original object itself.
const theIndex = data.indexOf('Ahmed');
if(theIndex !== -1) {
console.log("Found");
} else {
console.log("Not found");
}
const theIndex = data.includes('Ahmed');
if(theIndex !== false) {
console.log("Found");
} else {
console.log("Not found");
}
//------------------------------->First approach
const newData = [];
for(const name of data) {
newData.push(name);
}
console.log(newData)'
//------------------------------->Second approach
const newData = [];
for(let i=0; i<data.length; i++) {
newData.push(data[i]);
}
console.log(newData);
//----------------------------------> ProtoType
data.forEach((value, index, fullArray)=>{
});
//----------------------------------> Example, create a new array of first array elements as objects
const newData = [];
data.forEach((value, index, fullArray)=>{
const nameObj = {id: index, name:value};
newData.push(nameObj);
});
console.log(newData)
//------------------------------------------> for
const prices = [10, 15, 20, 10.99];
const tax = 0.19;
const taxAdjustedPrices= [];
for(const price of prices) {
taxAdjustedPrices.push(price * (1 + tax));
}
console.log(taxAdjustedPrices);
//------------------------------------------> forEach
const prices = [10, 15, 20, 10.99];
const tax = 0.19;
const taxAdjustedPrices= [];
prices.forEach((price, indx, allPrices)=>{
taxAdjustedPrices.push({id: indx, price: price*(1+tax)});
});
console.log(taxAdjustedPrices);
//---------------------------------> The difference between this and forEach is that map() function will return the element in every iteration, and this will be added to the new created array without the original array being touched.
const prices = [10, 15, 20, 10.99];
const tax = 0.19;
const taxAdjustedPrices = prices.map((price, indx, allPrices)=>{
const priceObj = {id: indx, price: price*(1+tax)};
return priceObj;
});
console.log(taxAdjustedPrices);
//------------------------------> Sort sorts based on the starting string, so it will not sort the numbers in a correct way
const prices = [10, 1.5, 20, 10.99];
const sortedPrices = prices.sort();
console.log(sortedPrices);
//output : (6) [1.5, 10, 10.99, 11, 13, 2], which is definitely not the sorting we need.
//------------------------------> Good way to sort numbers is as follows : because it compares two entries together
const prices = [10, 1.5, 11, 2, 13, 10.99];
const sortedPrices = prices.sort( (a,b)=> {
if(a > b) {
return 1;
} else if(a == b) {
return 0;
} else {
return -1;
}
});
console.log(sortedPrices);
//output : (6) [1.5, 2, 10, 10.99, 11, 13], which is the right sort.
//------------------------------> Same as above example
prices .sort(function(a, b){return a - b});
//------------------------------> Sorting Descending #1
const prices = [10, 1.5, 11, 2, 13, 10.99];
const sortedPrices = prices.sort( (a,b)=> {
if(a > b) {
return 1;
} else if(a == b) {
return 0;
} else {
return -1;
}
});
console.log(sortedPrices.reverse());
//output : (6) [1.5, 2, 10, 10.99, 11, 13], which is the right sort.
//------------------------------> Sorting Descending #2
const prices = [10, 1.5, 11, 2, 13, 10.99];
const sortedPrices = prices.sort( (a,b)=> {
if(a > b) {
return -1;
} else if(a == b) {
return 0;
} else {
return 1;
}
});
console.log(sortedPrices);
//output : (6) [1.5, 2, 10, 10.99, 11, 13], which is the right sort.
//-----------------------------> Sorting array of strings alphabitically whether starting with lower or uppercase:
["Foo", "bar"].sort(function (a, b) {
return a.toLowerCase().localeCompare(b.toLowerCase());
});
//-----------------------------> Solution#2
matchesFound.sort((a,b)=>{
if(a < b) return -1;
if(b < a) return 1;
return 0;
});
const prices = ['Ahmed', 'Nehad', 'Basem', 'Kamel'];
console.log(prices); //ouput: 'Ahmed', 'Nehad', 'Basem', 'Kamel'
console.log(prices.reverse()); //ouput: 'Kamel', 'Basem', 'Nehad', 'Ahmed'
const prices = [10, 1.5, 11, 2, 13, 10.99];
const filteredArray = prices.filter( (price, indx, fullArray)=>{
return price >= 10; //This will only return the elements that passes this condition
});
console.log(filteredArray);
//---------------------------------> A shorter way for the previous code will be :
const filteredArray = prices.filter( price => price >= 10);
//--------------------> Using forEach
const prices = [10, 1.5, 11, 2, 13, 10.99];
let sum = 0;
prices.forEach((price)=>{
sum += price;
});
console.log(sum);
//--------------------> Using for
const prices = [10, 1.5, 11, 2, 13, 10.99];
let sum = 0;
for( let i=0; i<prices.length; i++) {
sum += prices[i];
}
console.log(sum);
//--------------------------------> Prototype
/*
- previousVal : the previous/last value, first time it will be equal to the second parameter passed to reduce function which is 0 in our case
- currentVal: will be the current value of the element in the array.
- currIndex: the current element index.
- fullArray : is the full array being reduced.
*/
const sum = prices.reduce((previousVal, currentVal, CurrentIndx, fullArray)=>{
return previousVal + currentVal;
}, 0);
console.log(sum);
//------------------------------> Here is the example solution
const prices = [10, 1.5, 11, 2, 13, 10.99];
const sum = prices.reduce((previousVal, currentVal, indx, fullArray)=>{
return previousVal + currentVal;
}, 0);
console.log(sum);
//-----------------------------> A short version of the previous code
const prices = [10, 1.5, 11, 2, 13, 10.99];
const sum = prices.reduce((previousVal, currentVal)=> previousVal + currentVal, 0);
console.log(sum);
const prices = [10, 1.5, 11, 2, 13, 1.25, 10.99];
const leastValue = prices.reduce((previousVal, currentVal, indx, fullArray)=>{
if(previousVal == 0) {
return currentVal;
} else if(currentVal < previousVal){
return currentVal;
} else {
return previousVal;
}
}, 0);
console.log(leastValue);
//------------------------------------> Another short version
const leastValue = prices.reduce((previousVal, currentVal, indx, fullArray)=>{
return (currentVal < previousVal)?currentVal:previousVal;
});
//----------------------------------> A third short version
const leastValue = prices.reduce((previousVal, currentVal, indx, fullArray)=>{
if(currentVal < previousVal){
return currentVal;
} else {
return previousVal;
}
});
//--------------------------------------> Another very efficient way .. using the spread operator, which will get all the elements of the array
console.lo(Math.min(...prices));
const prices = [10, 1.5, 11, 2, 13, 1.25, 10.99];
const greatestValue = prices.reduce((previousVal, currentVal, indx, fullArray)=>{
return (currentVal < previousVal)?previousVal:currentVal;
});
console.log(greatestValue);
//--------------------------------------> Another very efficient way .. using the spread operator, which will get all the elements of the array
console.lo(Math.max(...prices));
const originalArray = [{price: 350},{price: 100},{price: 50},{price: 410}];
const transformedArray = originalArray.map(item=>item.price); //output [350,100,50,410]
const sum = transformedArray.reduce((sumVal, currVal)=>sumVal + currVal, 0); //output: 910
console.log(transformedArray, sum);
//----------------> Another solution without map
const sum2 = originalArray.reduce((sumVal, currVal)=>sumVal + currVal.price, 0);
console.log(sum2); //output: 910
//----------------> Athird shorter chaining map and reduce
sum3 = originalArray.map(item=>item.price).reduce((sumVal, currVal)=>sumVal + currVal,0);
console.log(sum3); //output: 910
//---------------------->ProtoType
//string.split('separator', numberOfElements);
//---------------------->Example
const stringData = "Mohammed;10.99;2001";
const transformedData = stringData.split(";");
console.log(transformedData); //output: ['Mohammed', 10.99, 2001];
const nameFragments = ['Mohammed', 10.99, 2001];
const nameString = nameFragments.join(",");
console.log(nameString); //output: Mohammed,10.99,2001
//----------------------------> Solution #1
var fruits = ["Banana", "Orange", "Apple", "Mango"];
typeof fruits; // returns object, this might be a problem
//----------------------------> Solution #2
Array.isArray(fruits); // Will return true if fruits is an array, bu this is not supported in old browsers
//----------------------------> Solution #3
function isArray(x) {
return x.constructor.toString().indexOf("Array") > -1;
}
//----------------------------> Solution #4
fruits instanceof Array; // returns true