How to split a long array into smaller arrays, with JavaScript
return myarr.every(val => val === 'true');
var size = 10; var arrayOfArrays = [];
for (var i=0; i
Immutability in JavaScript - When and Why Should You Use It
All about Immutable Arrays and Objects in JavaScript
Immutable Array functions
Immutable functions , which means the actual array will not be modified. Always new array will be created.
The find method lets you iterate through an array and executes specific function you pass as a callback.
var arrOfNumbers = [4,5,6,7,8,9,12,3,4,44];
//Find the first even number and store it inside a variable.
let firstEvenNumber = arrOfNumbers.find(function(number) {
return number % 2 !== 1;
})
console.log("firstEvenNumber : ", firstEvenNumber);
let greaterThanTen = arrOfNumbers.filter(function(number) {
return number > 10;
})
console.log("greaterThanTen : ", greaterThanTen)
let addedValue = arrOfNumbers.map(function(number) {
return number + 10;
})
console.log("addedValue : ", addedValue)
//OUTPUT :
firstEvenNumber : 4
greaterThanTen : [12, 44]
addedValue : [14, 15, 16, 17, 18, 19, 22, 13, 14, 54]
Reducer
The reduce method works with two parameters, accumulator and currentValue. Well, it uses four parameters, but two are optioanl. It then returns a single value based on a reucer function you provided as a callback.
The accumulator stores the previous value returned by reducer function.
var arrOfNumbers = [4,5,6 ];
let sumTotal = arrOfNumbers.reduce(function(accumulator, currentValue){
console.log('accumulator : ', accumulator + ' - currentValue : ' + currentValue);
return accumulator + currentValue;
})
console.log('Sum of Total : ' , sumTotal)
//OUTPUT :
//accumulator : 4 - currentValue : 5
//accumulator : 9 - currentValue : 6
//Sum of Total : 15
Array.from
Array.from () - Convert your arguments into iterable array
var args = "helloworld"
console.log(Array.from(args))
//OUTPUT :
["h", "e", "l", "l", "o", "w", "o", "r", "l", "d"]
Array.includes
include - checking either the array is available or not
var array = [4,5,6,7,8];
console.log(array.includes(9))
//OUTPUT :
false
Splice
//To remove element use index, count
var arr = [6,7,8,9,0];
console.log(arr.splice(0,2))
//To copy an element use splice 0
var arrCopy = arr.splice(0)
console.log('Copy of Array : ',arrCopy)
Remove object from array of objects in Javascript
// source: http://stackoverflow.com/questions/16491758/remove-objects-from-array-by-object-property
// we have an array of objects, we want to remove one object using only the id property
var apps = [{id:34,name:'My App',another:'thing'},{id:37,name:'My New App',another:'things'}];
// get index of object with id:37
var removeIndex = apps.map(function(item) { return item.id; }).indexOf(37);
// remove object
apps.splice(removeIndex, 1);
let files = [
{ filecode: '1',
filedate: '20180430',
amountinfile: '55' },
{ filecode: '2',
filedate: '20180429',
amountinfile: '2'},
{ filecode: '3',
filedate: '20180429',
amountinfile: '97' },
{ filecode: '4',
filedate: '20180428',
amountinfile: '101' }
];
let alreadyHaveFiles = [ '3','1','2'];
let tempFiles = files.slice(0);
console.log('Before:\n',files.length, tempFiles.length);
tempFiles.forEach((element) => {
if(alreadyHaveFiles.includes(element['filecode'])){
let removeIndex = files.map((item) => item['filecode']).indexOf(element['filecode']);
console.log(removeIndex)
files.splice(removeIndex, 1);
}
});
console.log('After:\n',files.length, tempFiles.length)
//remove a single object from a array of objects
//apps.splice( apps.findIndex(a => a.id === 37) , 1);
//OUTPUT :
Before: 4 4
After: 1 4
Array.push() : Adding Element at the end of an Array
number_arr = [ 10, 20, 30, 40, 50 ];
number_arr.push(60);
Array.pop() : Removing elements from the end of an array
number_arr = [ 20, 30, 40, 50 ];
number_arr.pop();
Array.unshift() : Adding elements at the front of an Array
var num = [20,30,40]
num.unshift(10,20)
console.log("num : " , num )
let string_arr = [ "amit", "sumit" ];
string_arr.unshift("anil", "sunil");
console.log("string_arr : " , string_arr )
//Output :
num : [10, 20, 20, 30, 40]
string_arr : ["anil", "sunil", "amit", "sumit"]
Array.shift() : Removing elements at the beginning of an array
number_arr = [ 20, 30, 40, 50, 60 ];
// [30, 40, 50, 60];
number_arr.shift();
Array.prototype.every()
Syntax : arr.every(callback[,thisArg])
Array.Prototype.filter()
Description: Array.prototype.filter() is used to get a new array which has only those array elements which pass the test implemented by the callback function. It accepts a callback function as argument. This callback function has to return a true or false. Elements for which the callback function returned true are added to the newly returned array.
Sample use Cases:
1. Scenario where user has to remove all null values from an array.
2. Scenario where user has to filter out the array based on value of a particular property of objects in the array.
1.Function to filter out the students who got more than 80 percent marks.
function fnFilterStudents_filter(aStudent){
return aStudent.filter(function(oStudent){
return oStudent.fPercentage > 80.0
});
}
aStudent = [
{sStudentId : "001" , fPercentage : 91.2},
{sStudentId : "002" , fPercentage : 78.7},
{sStudentId : "003" , fPercentage : 62.9},
{sStudentId : "004" , fPercentage : 81.4}];
console.log(fnFilterStudents_filter(aStudent));
/*[
{ sStudentId: '001', fPercentage: 91.2 },
{ sStudentId: '004', fPercentage: 81.4 }
]*/
Array.Prototype.map()
Description:Array.prototype.map() is used to modify each element of the array according to the callback function. Array.prototype.map() calls the callback function once for each element in the array in order. The point to note is that callback function is called on indexes of elements who has assigned value including undefined.
The map() method creates a new array with the results of calling a function for every array element.
The map() method calls the provided function once for each element in an array, in order.
Note: map() does not execute the function for array elements without values.
Note: this method does not change the original array.
Sample use Cases:
1. Scenario where user has to reduce each amount in an array by a specific tax value
2. Scenario where user has to create a new property of every object in an existing array of objects.
1.Function to add property bIsDistinction to each object in the array.
let aStudent = [
{sStudentId : "001" , fPercentage : 91.2},
{sStudentId : "002" , fPercentage : 78.7},
{sStudentId : "003" , fPercentage : 62.9},
{sStudentId : "004" , fPercentage : 81.4}];
function fnAddDistinction_map(aStudent){
return aStudent.map(function(student, index, array){
student.bIsDistinction = (student.fPercentage >= 75.0) ? true : false;
return student;
});
}
console.log(JSON.stringify(fnAddDistinction_map(aStudent)));
//Output :
[{"sStudentId":"001","fPercentage":91.2,"bIsDistinction":true},{"sStudentId":"002","fPercentage":78.7,"bIsDistinction":true},{"sStudentId":"003","fPercentage":62.9,"bIsDistinction":false},{"sStudentId":"004","fPercentage":81.4,"bIsDistinction":true}]
2. Scenario where Array.prototype.Map() is used with standard JavaScript functions.
For example, with Math.sqrt to calculate square root of each element in an array or to parse string values to float.
[1,4,9].map(Math.sqrt); // Output : [1,2,3]
var temp = ["1","2","3"].map(
function (val) {
return parseInt(val,10);
}
);
//[ 1, 2, 3 ]
concat array - this method does not change the existing arrays but instead returns a new array.
spread Operators [...arr,...arr2] - for a large data set it will work slower
copying without the spread operator - when we mutate new array it will also affect the old array(the one which we copied) - We can make use of the spread operator in this case
Copy(like splice method) -
// copying without the spread operator
// changed the original array
let arr = ['a','b','c'];
let arr2 = arr;
arr2.push('d');
console.log(arr2);
console.log(arr); // even affected the original array(arr)
insert an element inside the array, the original array is also altered
Expand - Whenever we want to expand an array into another we do something like this
// normally used expand method
let arr = ['a','b'];
let arr2 = [arr,'c','d'];
console.log(arr2); // [ [ 'a', 'b' ], 'c', 'd' ]
Copy array in 3 Ways
1. var arr1 = arr2; if add element will add in source
2. splice
3. spread operator var arrNew = [...arr1]
Expand An array :
let arr = ['a','b'];
let arr2 = [arr,'c','d'];
//[ [ 'a', 'b' ], 'c', 'd' ]
// expand using spread operator
let arr = ['a','b'];
let arr2 = [...arr,'c','d'];
console.log(arr2); // [ 'a', 'b', 'c', 'd' ]
Rest parameter :
Rest parameter is an improved way to handle function parameter, allowing us to more easily handle various input as parameters in a function. The rest parameter syntax allows us to represent an indefinite number of arguments as an array. With the help of a rest parameter a function can be called with any number of arguments, no matter how it was defined. Rest parameter is added in ES2015 or ES6 which improved the ability to handle parameter.
Flatten an Array
// es6 rest parameter
function fun(...input){
let sum = 0;
for(let i of input){
sum+=i;
}
return sum;
}
console.log(fun(1,2)); //3
console.log(fun(1,2,3)); //6
console.log(fun(1,2,3,4,5)); //15
We were able to get the sum of all the elements that we enter in the argument when we call the fun() function. We get the sum of all the elements in the array by making use of the for..of loop which is used to traverse the iterable elements inside an array.
Note: The rest parameter have to be the last argument, as its job is to collect all the remaining arguments into an array. So having a function definition like the code below doesn’t make any sense and will throw an error.
What is a Closure?
A closure is a way to access and manipulate external variables from within a function.
slice-splice-split-methods-in-javascript
Slice ( )
Copies elements from an array
Returns them as a new array
Doesn’t change the original array
Starts slicing from … until given index: array.slice (from, until)
Slice doesn’t include “until” index parameter
Can be used both for arrays and strings
Splice ( )
Used for adding/removing elements from array
Returns an array of removed elements
Changes the array
For adding elements: array.splice (index, number of elements, element)
For removing elements: array.splice (index, number of elements)
Can only be used for arrays
Split ( )
Divides a string into substrings
Returns them in an array
Takes 2 parameters, both are optional: string.split(separator, limit)
Doesn’t change the original string
Can only be used for strings
There are many other built-in methods for JavaScript arrays and strings. If you learn the usage, these methods make your life easier in programming.
Reference
- Array Methods Cheatsheet
- javascript-essentials-arrays : AdvancedArray
- Intreview QA
- javascript-spread-operator
- javascript-rest-operator
- Online Editor
- javascript-basic-array-methods
- javascript-basic-array-methods
- must-use-javascript-array-functions-part-2
- javascript-splice-vs-slice
- removing-multiple-items-from-a-javascript-array