25
loading...
This website collects cookies to deliver better user experience
const mixedTypedArray = [100, true, 'freeCodeCamp', {}];
index 1
, 'freeCodeCamp' is at index 2
, and so on.How to Create an Array in JavaScript
unshift()
the method adds a new element to an array (at the beginning), and "unshifts" older elements:const fruits = [“Orange”, “Apple”, “Mango”, “Banana”,];
fruits.unshift(“Lemon”);
console.log(fruits)
push()
the method adds a new element to an array (at the end):const fruits = [“Orange”, “Apple”, “Mango”, “Banana”,];
fruits.push(“lemon”);
console.log(fruits);
shift()
the method removes the first array element and "shifts" all other elements to a lower index.const fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
fruits.shift();
console.log(fruits)
pop()
the method removes the last element from an array:const fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
fruits.pop();
console.log(fruits)
slice()
method slices out a piece of an array into a new array.const fruits = [“Banana”, “Orange”, “Lemon”, “Apple”, “Mango”];
const citrus = fruits.slice(1);
console.log(fruits)
slice()
the method creates a new array. It does not remove any elements from the source array.filter()
the method creates a new array filled with elements that pass a test provided by a function.filter()
the method does not execute the function for empty elements.filter()
the method does not change the original array.const users = [
{firstName: "Joe", lastName: "Doe"},
{firstName: "Alex", lastName: "Clay"},
{firstName: "Opie", lastName: "Winston"},
{firstName: "Wasten", lastName: "Doe"},
]
const newUser = users.filter(user => user.firstName == "Opie")
console.log(newUser)
reverse()
method reverses the order of the elements in an array.reverse()
method overwrites the original array.const array1 = ['one', 'two', 'three'];
console.log('array1:', array1); //["one", "two", "three"]
const reversed = array1.reverse();
console.log('reversed:', reversed); //["three", "two", "one"]
// Careful: reverse is destructive -- it changes the original array.
console.log('array1:', array1); //["three", "two", "one"]
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
console.log(fruits)