Arrays Flashcards
How to create an array?
const arr = [‘1’ , ‘2’, ‘3’];
How to read a subset of an arrary?
use slice(start,end)
use splice if original array needs to be modified.
how to concat two array?
arr1.concat(arr2)
how to reverse an array?
arr1.reverse()
how to add a separator to all elements in an array?
arr1.join(‘*’);
When to use [] and at in array?
to get the last element and also for chaining…
arr1.[arr1.lenth -1] == arr1.at(-1)
How to loop through an array using forEach?
const arr = [‘1’ , ‘2’, ‘3’];
arr.forEach(function(mov,i,arrayOriginal)
{
});
How to use forEach for Maps?
map.forEach(function(value, key, originalMap)
{
});
How to use forEach for sets?
set.forEach(function(value, key, originalSet)
{
});
value and key will be same for sets as there is no key in sets. We can omit using _
What are different data transformation methods available for arrays?
There are 3 methods-
map - If we need to use multiplier
filter - to filter the results
reduce - to have a single value
How to use array map method?
—–ArrayMapmethod—–
constmapArr=[456,787,125,672,572,135];
constnewMapArr=mapArr.map(function(value,i,arrMap){ console.log(`valueis${value}`); console.log(`iis${i}`); returnvalue*1; });
console.log(newMapArr);
—–Sameusingforof—–
for(constitemofmapArr){
console.log(samewithfor-of${item*1}
);
}
How to use filter method on arraya?
—–Arrayfiltermethod—–
constfilterArr=[456,787,125,672,572,135];
const newFilteredArr = filterArr.filter(function(mov,i,arr) { return mov>100; });
How to use reduce method for arrays?
—–Reducemethod—–
constreduceDemo=[430,1000,700,50,90];
constacc=reduceDemo.reduce(function(acc,value, i, originalArr){
returnacc+value;
},0);
console.log(acc);
Findthe largestnumber
constlargest=reduceDemo.reduce(function(acc,value){
if(acc
How to use find method?
Filter and find will search for an element. However, filter returns the array and find returns the single value (the first value).
—–Filter—-
constarrFilter=[29,45,23,78,54,53];
constfilterArr=arrFilter.filter(function(value,index,curr){
returnvalue
what is some and every method in arrays?
To remember use some and every CONDITION..
some returns true/false for some condition.
every returns true/false for every condition.
Includes method returns true/false if an element exists in the array.
But some method will return true/false if the condition is met. For every all elements should satisfy the condition.
arr.some(function(mov)
{
return mov>0;
}
How do you sort an array?
To sort an array, we need to use sort().
By default, it sorts based on the strings.
For numbers we need to provide the sort condition.
arr.sort(function(a,b) { if(a>b) return 1; else return -1 });