Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Lecture JS arrays

Uploaded by

i202480
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Lecture JS arrays

Uploaded by

i202480
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

JavaScript Arrays

JS Arrays

• JavaScript arrays are used to store


multiple values in a single variable.
cars = ["Saab", "Volvo", "BMW"];

//We can use Array with var, let and const


concat() function

The concat() method concatenates (joins) two or more arrays.

The concat() method does not change the existing arrays, but returns a new
array, containing the values of the joined arrays.

Array1.concat(Array2)
const item1 =
[“Apple",“Mango",“Orange"];

const item2 =
Example [“Banana",“Grapes",“PineApple"];

console.log(item1.concat(item2))
copyWithin() function

• The copyWithin() method copies array


elements to another position in an array,
overwriting the existing values.
• The copyWithin() does not add items to the
array.

array.copyWithin(target, start, end)


Example

const fruits = ["Banana", "Orange", "Apple", "Mango"];


fruits.copyWithin(2, 0);

let arr = [1, 2, 3, 4, 5, 6];


arr.copyWithin(2, 0, 3);
console.log(arr);
• The entries() method returns an Array Iterator object
with key/value pairs.
• For each item in the original array, the new iteration
object will contain an array with the index as the key,
and the item value as the value:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
entries() [0, "Banana"]

function [1, "Orange"]


[2, "Apple"]
[3, "Mango"]

• entries() does not change the original array.


const fruits = ["Banana", "Orange", "Apple", "Mango"];
const iterator1 = fruits.entries();
for (var e of iterator1) {
console.log(e);
}

Examples // iterate through key-value gracefully


const obj = { a: 5, b: 7, c: 9 };
for (const [key, value] of Object.entries(obj)) {
console.log(`${key} ${value}`);
// "a 5", "b 7", "c 9"
}
The fill() method fills specified
elements in an array with a
static value.

You can specify the position of


fill() where to start and end the
filling. If not specified, all
function elements will be filled.

array.fill(value, start, end)


• //start and end are optional
Example

const array1 = [1, 2, 3, 4];

console.log(array1.fill(0, 2, 3));
Example

const array1 = [1, 2, 3, 4];

console.log(array1.fill(0));
Example

const array1 = [1, 2, 3, 4];

console.log(array1.fill(7,2));
The filter() method creates an array
filled with all array elements that pass a
test

filter() filter() does not execute the function for


function empty array elements.

filter() does not change the original


array.
Example

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present’];

const result = words.filter(word => word.length > 6);

console.log(result);
find() function
• The find() method returns the value of the array element
that passes a test.
• The method executes the function once for each element
present in the array:

• If it finds an array element where the function returns a true


value, find() returns the value of that array element (and does
not check the remaining values)
• Other wise it returns undefined
Example

const array1 = [5, 12, 8, 130, 44];

const found = array1.find(element => element > 10);

console.log(found);
map() function

• The map() method creates a new array with the results of calling a function
for every array element.
• The map() method calls the provided function once for each element in an
array, in order.
• map() does not execute the function for empty elements.
• map() does not change the original array.
Example

const array1 = [1, 4, 9, 16];


const map1 = array1.map(x => x * 2);
console.log(map1);
forEach() function

The forEach() method calls a function once for


each element in an array, in order.

forEach() is not executed for array elements


without values.
const array1 = ['a', '2', 'c'];
Example array1.forEach(element => console.log(element));
reduce() function

The reduce() method executes a reducer function for each value of an array.

reduce() returns a single value which is the function's accumulated result.

reduce() does not execute the function for empty array elements.

reduce() does not change the original array.


Reduce()
• array.reduce(callback(accumulator, currentValue, index, array), initialValue)
• callback: The function to execute on each element in the array, with these
parameters:
• accumulator: Holds the accumulated result from each iteration. The accumulator is
updated as the function iterates through the array.
• currentValue: The current element being processed in the array.
• index (optional): The index of the current element being processed. array (optional):
• The array reduce() is called upon.
• initialValue (optional): The initial value for the accumulator. If omitted, the
first element of the array is used as the initial accumulator value, and the
iteration starts from the second element.
const array1 = [1, 2, 3, 4];
function reducer(previousValue, currentValue) {
return (previousValue + currentValue); }
console.log(array1.reduce(reducer));
Example _______________________________
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((accumulator, currentValue) =>
accumulator + currentValue, 0);
console.log(sum);
•When an initialValue is provided:
•The accumulator is set to this initialValue.
•The currentValue starts from the first element of the array.
•When no initialValue is provided:
•The accumulator starts as the first element of the array.
•The currentValue starts from the second element of the
array.
slice() function

• The slice() method returns selected elements in an array,


as a new array.
• slice() selects the elements starting at the given start
argument, and ends at, but does not include, the given
end argument.
• slice() does not change the original array.
array.slice(start, end)
const animals = ['ant', 'owl', 'camel', 'duck',
'elephant'];
console.log(animals.slice(2));

console.log(animals.slice(2, 4));

Example console.log(animals.slice(1, 5));

console.log(animals.slice(-2));

console.log(animals.slice(2, -1));
pop() function

• The pop() method removes the last element of an


array.
• pop() returns the element it removes.
• pop() changes the length of the array.
array.pop()
• Use shift() to remove element from first position.
const plants = ['broccoli', 'onion', 'cabbage', 'tomato’];
console.log(plants.pop());
Example console.log(plants);
console.log(plants.shift());
console.log(plants);
push() function

• The push() method adds new items to the


end of an array.
• push() changes the length of the array and
returns the new length.
• To add items at the beginning of an array, use
unshift().

array.push(item1, item2, ..., itemX)


const animals = [‘horse', 'goats', 'sheep’];
const count = animals.push('cows’);
console.log(count);
console.log(animals);

Example animals.push('chickens', 'cats', 'dogs’);


console.log(animals);

animals.unshift(‘FirstAnimal’);
console.log(animals);
flat() method that creates a new array with
all the elements of the subarrays
concatenated to it recursively up to a
specified depth.

By default, the depth is ‘1’.


flat()
function

We can also use ‘Infinity’ parameter for all


sub arrays.
const numbers = [1, 2, [3, 4, 5]];

const flatNumbers = numbers.flat(); Example


(1)
console.log(flatNumbers);
const numbers = [1, 2, [3, 4, 5, [6, 7]]];
const flatNumbers = numbers.flat(2);
console.log(flatNumbers);
Example (2)
const numbers1 = [1, 2, [3, 4, 5, [6, 7, [8, 9]]]];
const flatNumbers1 = numbers1.flat(Infinity);
console.log(flatNumbers1);
The sort() method sorts
an array alphabetically.

sort() The reverse() method


reverses the elements in
function an array.

Both methods changes


the original array.
const fruits = ["Banana", "Orange", "Apple", "Mango"];
Example console.log(fruits.sort());
console.log(fruits.reverse());

You might also like