22
loading...
This website collects cookies to deliver better user experience
let items = ["Apples", "Bananas", 2, 4, 8, "Purple", true, false]
let items = [1, 2, 3, ["Apples", "Bananas"]]
let/const/var arrayName = []
let items = [1, 2, 3, 4, 5]
let thirdElement = items[2]
array.length
let items = [1, 2, 3, 4, 5]
items.forEach(item => console.log(item))
// for each loop is used to access each element present inside the array
let items = [1, 2, 3, 4, 5]
for(let i=0; i< items.length; i++) {
console.log(items[i])
}
// The above loop will print each item to the console
// items.length contains the value 5 because array contains 5 elements
// hence the loop will run until the value of i is less than 5
let items = [1, 2, 3, 4, 5]
items[2] = 10
let items = [1, 2, 3, 4, 5]
// get length of an array
console.log(items.length) // prints 5
/*
add and remove elements from the end of the array
push - adds element at the end of the array
pop - removes element from the end of the array
*/
// add element at the end of an array
items.push(6) // returns [1, 2, 3, 4, 5, 6]
items.push(7, 8) // returns [1, 2, 3, 4, 5, 6, 7, 8]
/* At this point,
items = [1, 2, 3, 4, 5, 6, 7, 8]
*/
// remove element from the end of an array
items.pop() // returns [1, 2, 3, 4, 5, 6, 7]
let removedValue = items.pop()
console.log(removedValue) // prints 7
/* At this point,
items = [1, 2, 3, 4, 5, 6]
*/
// check if element is present inside array or not
console.log(items.includes(10)) // prints false
console.log(items.includes(1)) // prints true
/*
find index of array elements
indexOf - returns index of the first occurrence of the element
lastIndexOf - returns index of the last occurrence of the element
*/
let box = ["pen", "pencil", "eraser", "pen", "pen"]
console.log(box.indexOf("pen")) // prints 0
console.log(box.lastIndexOf("pen")) // prints 4
/*
add and remove elements from the beginning of the array
shift - removes the first element from the array
unshift - add element at the beginning of the array
*/
let items = [1, 2, 3]
items.shift() // returns [2, 3]
items.unshift(0, 1) // returns [0, 1, 2, 3]
/*
sort - sorts an array in increasing order
to sort array in decreasing order, you have to pass comparison function
to the sort
syntax - array.sort()
*/
let items = [ 5, 4, 3, 1, 2]
items.sort() // returns [1, 2, 3, 4, 5]
// sort in decreasing order
let items = [ 5, 4, 3, 1, 2]
items.sort((a,b)=>{
if(a<b){
return 1;
}else if(a>b){
return -1;
}else{
return 0;
}
})
// returns [5, 4, 3, 2, 1]
/*
slice - returns a portion of array without modifying the array
syntax - slice(start, end), slice(start)
slice does not return element present at the end index specified
*/
let items = [ 5, 4, 3, 1, 2]
console.log(items.slice(2)) // returns [3, 1, 2]
console.log(items.slice(2,4)) // returns [3, 1]