Javascript (JS) Data Structures: Arrays
Javascript (JS) Data Structures: Arrays
ARRAYS
JAVASCRIPT (JS) DATA STRUCTURES
ARRAYS
LENGTH PROPERTY
console.log(daysOfWeek.length);
JAVASCRIPT (JS) DATA STRUCTURES
EXERCÍCIO
<script>
var fibonacci = [];
fibonacci[1] = 1;
fibonacci[2] = 1;
for(var i = 3; i < 20; i++){
fibonacci[i] = fibonacci[i-1] + fibonacci[i-2];
}
for(var i = 1; i<fibonacci.length; i++){
console.log(fibonacci[i]);
}
</script>
JAVASCRIPT (JS) DATA STRUCTURES
numbers.splice(5,3);
▸ the following code will add three elements starting from 5 index.
This means that will be insert to the numbers array the numbers 2,
3, and 4.
numbers.splice(5,0,2,3,4);
ARRAY
METHODS
JAVASCRIPT (JS) DATA STRUCTURES
Loiane Groner
JS ARRAY METHODS
JS ARRAY METHODS
EVERY METHOD
var isEven = function (x) {
// returns true if x is a multiple of 2.
console.log(x);
return (x % 2 == 0) ? true : false;
};
var numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
numbers.every(isEven);
▸ The every method will iterate each element of the array until the return
of the function is false.
▸ In this case, our first element of the numbers array is the number 1. 1
is not a multiple of 2 (it is an odd number), so the isEven function will
return false and this will be the only time the function will be
executed.
JS ARRAY METHODS
SOME METHOD
var isEven = function (x) {
// returns true if x is a multiple of 2.
console.log(x);
return (x % 2 == 0) ? true : false;
};
var numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
numbers.some(isEven);
▸ The same behavior as the every method, however, the some method will
iterate each element of the array until the return of the function is true .
▸ In our case, the first even number of our numbers array is 2 (the second
element). The first element that will be iterated is number 1; it will return
false. Then, the second element that will be iterated is number 2, and it
will return true—and the iteration will stop.
JS ARRAY METHODS
FOREACH
▸ It has the same result as using a for loop with the function's
code inside it:
var numbers.forEach(function(x){
console.log((x % 2 == 0));
});
JS ARRAY METHODS
MAP
FILTER
▸ Iterate and It returns a new array with the elements that the
function returned true:
var isEven = function (x) {
▸ . return (x % 2 == 0) ? true : false;
};
var numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
var evenNumbers = numbers.filter(isEven);
REDUCE
SORTING AN ARRAY
SORTING RULES
SORTING RULES
SORTING RULES
SORTING STRINGS
SORTING STRINGS
names.sort(function(a, b){
if (a.toLowerCase() < b.toLowerCase()){
return -1
}
if (a.toLowerCase() > b.toLowerCase()){
return 1
}
return 0;
});
TEXTO