DEV Community

Discussion on: What's the craziest code you ever read?

Collapse
 
mzahraei profile image
Ardalan

var multiDArray = [[7,8], [3,4], [1,2], [5,6]];
multiDArray.sort(function(a,b){
return a[0] - b[0];
});
console.log(multiDArray); //returns [[1,2], [3,4], [5,6], [7,8]];

You want to perform an operation on each element inside an array, in ascending order.
The forEach() method allows you to perform a callback function on each element of the array, in ascending order.

var myArray = [9, 2, 7, 6, 8, 5, 3];
myArray.forEach(function(element, index, array){
console.log(element + ' element'); //returns 9, 2, 7, 6, 8, 5, 3
console.log(element + ' index '); //returns 0 ,1, 2, 3, 4, 5, 6
.....
});

You need an array of only the elements that meet some certain criteria.
var myArray = [9, 2, 7, 6, 8, 5, 3];
var elementsOver5 = myArray.filter(function(element){
return element > 5;
});

You want to reduce the elements into a single value.
var numArray = [1,2,3,4,5,6];
var reducedValue = numArray.reduce(function(prev, current){
return prev + current;
});

You need to find either the largest or smallest number in an array.
var numArray = [2,2,3,6,7,7,7,7,8,9];
console.log(Math.max.apply(null, numArray));