Questions On Arrays

Max , Min ,Sort, and Filtering(null ,undefined, false, NaN)

				
					/*1 (...arr) */
var arr = [11,2,3,4,5]
console.log(...arr);//11 2 3 4 5 

/*2 Math.max(...arr)*/
console.log(Math.max(...arr));//11
console.log(arr.sort((a,b)=>b-a));//[ 11, 5, 4, 3, 2 ]
console.log(arr.sort((a,b)=>a-b));//[ 2, 3, 4, 5, 11 ]

/*Filtering null undefined null false*/
var array = ['a',NaN,null,undefined,false,1,3,5.4]
var array1 = array.filter(x=>Boolean(x));//same
var array2 = array.filter(x=>x!==undefined && x!==null);
var array3 = array.filter(x=>x);//same
var array4 = array.filter(x=>!!x);//same

console.log("array",array);
console.log("array1",array1);//filters - null,undefined,NaN,false 
console.log("array2",array2);//filters - null,undefined, 
console.log("array3",array3);//filters - null,undefined,NaN,false 
console.log("array4",array4);//filters - null,undefined,NaN,false 

/* OUTPUT
array1 [ 'a', 1, 3, 5.4 ]
array2 [ 'a', NaN, false, 1, 3, 5.4 ]
array3 [ 'a', 1, 3, 5.4 ]
array4 [ 'a', 1, 3, 5.4 ]
*/

/*find max and min in an arrry
   var arr = [11,2,3,4,5]
*/
console.log([Math.max(...arr),Math.min(...arr)]);
//OUTPUT :- [ 11, 2 ]


				
			

Different ways to empty an array

				
					var arr = [10, 20, 30, 40];

1.
arr.length = 0;

2.
arr = [];

3.
while (arr.length > 0) {
  arr.pop();
}

4.
arr.splice(0, arr.length);

				
			

Leave a Comment