Array Methods in JavaScript
// Array of Companies
const companies = [
{name: “Nova Investment”, category: “Finance”, start: “1980”, end: “2003”},
{name: “Shoprite”, category: “Retail”, start: “1992”, end: “2008”},
{name: “Ford Motors”, category: “Auto”, start: “1999”, end: “2007”},
{name: “Alaba Electronics”, category: “Retail”, start: “1989”, end: “2010”},
{name: “PedroTech”, category: “Technology”, start: “2009”, end: “2014”},
{name: “UBA”, category: “Finance”, start: “1987”, end: “2010”},
{name: “BMW”, category: “Auto”, start: “1986”, end: “1996”},
{name: “GSAP”, category: “Technology”, start: “2011”, end: “2016”},
{name: “Ivy Restaurant”, category: “Retail”, start: “1981”, end: “1989”}
];
// forEach() Method
// (method) Array.forEach(callbackfn: (value: {}[]) => void, thisArg?: any): void
// Performs the specified action for each element in an array.
// @param callbackfn — A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.
// @param thisArg — An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
for (let i = 0; i < companies.length; i++) {
log(companies[i]);
}
companies.forEach(function (company) {
log(company);
});
companies.forEach(company => log(company));
companies.forEach(chi => log(chi.name+’: ‘, chi.category+’, Duration -’, chi.end — chi.start));
// Array of Ages
const agesNum = [33, 16, 5, 54, 12, 21, 44, 20, 61, 13, 15, 45, 25, 64, 32];
// filtering with for() Loop, if Statement and push() Method
let age21up = [];
for (let i = 0; i < agesNum.length; i++) {
if (agesNum[i] >= 21) {
age21up.push(agesNum[i]);
}
}
log(age21up);
// filter() Method
// (method) Array<number|string>.filter(predicate: (value: number|string, index: number, array: number[]|string[]) => unknown, thisArg?: any): number[] (+1 overload)
// (method) Array<{ name: string; category: string; start: string; end: string; }>.filter(predicate: (value: {})
// Returns the elements of an array that meet the condition specified in a callback function.
// @param predicate — A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.
// @param thisArg — An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.
// Example 1
const age21plus = ages.filter(function (age) {
if (age >= 21) {
return true;
}
})
console.log(age21plus);
// Example 2
let age21plu = ages.filter(function (age) {
return age >= 21;
})
console.log(age21plu);
// Example 3
let age21pl = ages.filter(age => age >= 21);
console.log(age21pl);
// Example 4
// filtering ages from 21 to 61
let age21p = ages.filter(age => age >= 21 && age <= 61);
console.log(age21p);
// Example 5
// filtering retail companies
const retailCompanies1 = companies.filter(function (company) {
if (company.category === ‘Retail’) {
return true;
}
});
console.log(retailCompanies1);
// Example 6
const retailCompanies2 = companies.filter(company => company.category === ‘Retail’);
console.log(retailCompanies2);
// Example 7
// filter 80s companies
const companies80s = companies.filter(company => company.start >= 1980 && company.start < 1990);
console.log(companies80s);
// Example 8
// filter companies that have been operating for 10 or more years
const companies10plus = companies.filter(company => (company.end — company.start) >= 10);
console.log(companies10plus);
// [].map() Method
// map calls a defined callback function on each element of an array, and returns an array that contains the results.
// @param callbackfn — A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
// @param thisArg — An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
// Example 1
const companyNames = companies.map(company => company.name);
console.log(companyNames);
// [ “Nova Investment”, “Shoprite”, “Ford Motors”, “Alaba Electronics”, “PedroTech”, “UBA”, “BMW”, “GSAP”, “Ivy Restaurant” ]
// Example 2
const testMap1 = companies.map(function(company) {
return `${company.name} [${company.start} — ${company.end}]`;
});
console.log(testMap1);
// [ “Nova Investment [1980–2003]”, “Shoprite [1992–2008]”, “Ford Motors [1999–2007]”, “Alaba Electronics [1989–2010]”, “PedroTech [2009–2014]”, “UBA [1987–2010]”, “BMW [1986–1996]”, “GSAP [2011–2016]”, “Ivy Restaurant [1981–1989]” ]
// Example 3
const testMap2 = companies.map(company => `${company.name} [${company.end — company.start}]`);
console.log(testMap2);
// [ “Nova Investment [23]”, “Shoprite [16]”, “Ford Motors [8]”, “Alaba Electronics [21]”, “PedroTech [5]”, “UBA [23]”, “BMW [10]”, “GSAP [5]”, “Ivy Restaurant [8]” ]
// Array of Companies
const companies = [
{name: “Nova Investment”, category: “Finance”, start: “1980”, end: “2003”},
{name: “Shoprite”, category: “Retail”, start: “1992”, end: “2008”},
{name: “Ford Motors”, category: “Auto”, start: “1999”, end: “2007”},
{name: “Alaba Electronics”, category: “Retail”, start: “1989”, end: “2010”},
{name: “PedroTech”, category: “Technology”, start: “2009”, end: “2014”},
{name: “UBA”, category: “Finance”, start: “1987”, end: “2010”},
{name: “BMW”, category: “Auto”, start: “1986”, end: “1996”},
{name: “GSAP”, category: “Technology”, start: “2011”, end: “2016”},
{name: “Ivy Restaurant”, category: “Retail”, start: “1981”, end: “1989”}
];
// Array of Ages
const agesNum = [33, 16, 5, 54, 12, 21, 44, 20, 61, 13, 15, 45, 25, 64, 32];
// [].reduce() Method
// [].reduce() method dwells on Array of numbers and a callbackfn function. (callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: number[]) => number, initialValue: number): number (+2 overloads).
// Reduce calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
// Its parameter is a callbackfn function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
// Its parameter is an initialValue — If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
// Example 0 — for() Loop Method vs reduce() Method
let ageSum1 = 0
for (let i = 0; i < agesNum.length; i++) {
ageSum1 += agesNum[i];
}
console.log(ageSum1);
// 460
// Example 1
const ageSum2 = agesNum.reduce(function (sum, age) {
return sum + age;
}, 0)
console.log(ageSum2);
// 460
// Example 2
const ageSum3 = agesNum.reduce((sum, age) => sum + age, 0);
console.log(ageSum3);
// 460
// Example 3 — get total years for all companies
const totalYears1 = companies.reduce(function(total, company) {
return total + (company.end — company.start);
}, 0);
console.log(totalYears1);
// 119
// Example 4
const totalYears2 =
companies.reduce((total, company) => total + (company.end — company.start), 0);
console.log(totalYears2);
// 119
// COMBINED Array Methods
// Example 1
const thoseNumbers = [33, 16, 5, 54, 12, 21, 44, 20, 61, 13, 15, 45, 25, 64, 32];
const someNums = [];
const combinedMethods = thoseNumbers
.map(aNum => aNum * 2)
.filter(aNum => aNum >= 40)
.sort((a, b) => a — b)
.reduce((acc, aNum) => acc + aNum, 0);
console.log(combinedMethods);
// 798
// [].join() Method
// (method) Array<string>.join(separator?: string | undefined): string
// Adds all the elements of an array into a string, separated by the specified separator string.
// @param separator — A string used to separate one element of the array from the next in the resulting string. If omitted, the array elements are separated with a comma.
// Example 1
const numAr = [3, ‘L9’, 45, ‘V8’, 100, ‘u&’, ‘me’];
console.log(numAr.join(‘=’));
// 3=L9=45=V8=100=u&=me
// Example 2
const okey = [‘key’, ‘mapping’, ‘value’, ‘film’, ‘Dame’];
okeyJoin = okey.join(‘!&?’);
console.log(okeyJoin);
// key!&?mapping!&?value!&?film!&?Dame
// [].indexOf() Method
// (method) Array<string | number>.indexOf(searchElement: string | number, fromIndex?: number | undefined): number
// Returns the index of the first occurrence of a value in an array, or -1 if it is not present.
// @param searchElement — The value to locate in the array.
// @param fromIndex — The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.
const stVn = [3, ‘Okwe17’, 45, 100, -5, -35, ‘U’, -50, ‘19’, ‘Ada’, -32, -25];
console.log(stVn.indexOf(100));
// 3
// [].lastIndexOf() Method
// (method) Array<string | number>.lastIndexOf(searchElement: string | number, fromIndex?: number | undefined): number
// Returns the index of the last occurrence of a specified value in an array, or -1 if it is not present.
// @param searchElement — The value to locate in the array.
// @param fromIndex — The array index at which to begin searching backward. If fromIndex is omitted, the search starts at the last index in the array.
console.log([‘me’, 100, -5, -35, ‘me’, -50, -19, ‘just’, ‘me’].lastIndexOf(‘me’));
// 8
const numAr2 = [3, -9, 45, ‘me’, 100, -5, -35, ‘me’, -50, -19, ‘just’, ‘me’, ‘and’, ‘u’];
console.log(numAr2.lastIndexOf(‘me’)); // 11
// [].toLocaleString() Method
// (method) Array<never>.toLocaleString(): string
// Returns a string representation of an array. The elements are converted to string using their toLocaleString methods.
// Example 1
const toLS = [‘Dover’, ‘Bob’, ‘Dr’, ‘Ba’, ‘Biz’, ‘Edu’];
console.log(toLS.toLocaleString());
//Dover,Bob,Dr,Ba,Biz,Edu
// [].toString() Method
(method) Array<string | number>.toString(): string
Returns a string representation of an array.
[].toString() is a function that has no parameter.
// Example 1
const numAr = [3, -9, 45, 100, -5, -35, -15, -32, -25];
console.log(numAr.toString());
// 3,-9,45,100,-5,-35,-15,-32,-25
// Example 2
console.log([‘k’, ‘l’, ‘luk’, 5, ‘34’, ‘me’, ‘and’, 17].toString());
// k,l,luk,5,34,me,and,17
// [].shift() Method
// (method) Array<string | number>.shift(): string | number | undefined
// Removes the first element from an array and returns it. If the array is empty, undefined is returned and the array is not modified.
// Example 1
const numAr = [3, -9, 45, 100, -5, -35,-50, -19, -15, -32, -25];
console.log(numAr.shift());
// 3
// Example 2
const emptyAr = [];
console.log(emptyAr.shift());
// undefined
// Example 3
const someNames = [‘Jimmy’, ‘Toby’, ‘Okey’, 4, ‘Nna’, ‘Oby’];
console.log(someNames.shift());
// Jimmy
// [].push() Method
newArray.push(…items: any value)
// The push() Method appends new elements to the end of an Array. It returns the new Array with new length and values.
// It helps in changing array and its values in so many ways. When the push() Method is combined with Loops and Conditional Statements, original values are changed based on condition and pushed into another Array.
// The composite nature of the push() Method and its innumerable use, makes it a fundamental JavaScript Method for writing a program or developing an application.
// Example 1 — push() Method with Loop and Conditional Statements
// as filter, to create Array of odd numbers
const numAr = [3, -9, 45, 100, -5, -35, 10, -2, -50, -19, -15, -32, -25, -9, 17, 2, 4, 0, 8, 1, 6 ];
const push1ages = [];
for (let i = 0; i < ages.length; i++) {
if (ages[i] % 2 === 1) {
push1ages.push(ages[i]);
}
}
console.log(push1ages);
// [ 33, 5, 21, 61, 13, 15, 45, 25 ]
// Example 2 — push() Method with Loop and Conditional Statements
// as Filter, to create Array of even numbers
const numAr = [3, -9, 45, 100, -5, -35, 10, -2, -50, -19, -15, -32, -25, -9, 17, 2, 4, 0, 8, 1, 6 ];
const push2Comp = [];
for (let i = 0; i < ages.length; i++) {
if (ages[i] % 2 === 0) {
push2Comp.push(ages[i]);
}
}
console.log(push2Comp);
// [ 16, 54, 12, 44, 20, 64, 32 ]
// Example 3 — push() Method with Loop and Conditional Statements
// as Filter, to create Array of negative numbers
const numAr = [3, -9, 45, 100, -5, -35, 10, -2, -50, -19, -15, -32, -25, -9, 17, 2, 4, 0, 8, 1, 6 ];
const push3Comp = [];
for (let i = 0; i < numAr.length; i++) {
if (numAr[i] < 0) {
push3Comp.push(numAr[i]);
}
}
console.log(push3Comp);
// [ -9, -5, -35, -50, -9, -15, -32, -25, -9 ]
// Example 4 — push() Method with Loop and Conditional Statements
// as Filter, to create Array of positive numbers
const numAr = [3, -9, 45, 100, -5, -35, 10, -2, -50, -19, -15, -32, -25, -9, 17, 2, 4, 0, 8, 1, 6 ];
const push4numAr = [];
for (let i = 0; i < numAr.length; i++) {
if (numAr[i] >= 0) {
push4numAr.push(numAr[i]);
}
}
console.log(push4numAr);
// [ 3, 45, 100, 10, 0, 17, 2, 4, 0, 8, 1, 6 ]
// Example 5 — push() Method with Loop and Conditional Statements
// as Filter, to create Array of numbers, from -10 to 10.
const numAr = [3, -9, 45, 100, -5, -35, 10, -2, -50, -19, -15, -32, -25, -9, 17, 2, 4, 0, 8, 1, 6 ];
const push5numAr = [];
for (let i = 0; i < numAr.length; i++) {
if (numAr[i] <= 10 && numAr[i] >= -10) {
push5numAr.push(numAr[i]);
}
}
console.log(push5numAr);
// [ 3, -9, -5, 10, -2, -9, 2, 4, 0, 8, 1, 6 ]
// Example 6
// push() Method with an array of numbers and strings
// (method) Array<string | number>.push(…items: (string | number)[]): number
// Appends new elements to the end of an array, and returns the new length of the array.
// @param items — New elements to add to the array.
const child = [‘Baby’, 0, ‘kid’, ‘children’, ‘kindergaten’];
console.log(child.push(‘underage’, ‘minor’, 4));
// 8
console.log(child);
// [ “Baby”, 0, “kid”, “children”, “kindergaten”, “underage”, “minor”, 4 ]
// [].unshift() Method
// (method) Array<string | number>.unshift(…items: (string | number)[]): number
// Inserts new elements at the start of an array, and returns the new length of the array.
// @param items — Elements to insert at the start of the array.
// Example 1
const FruitsArr = [‘Orange’, ‘Banana’, ‘Pear’, ‘Mango’, ‘Pawpaw’];
console.log(FruitsArr.unshift(‘Pineapple’, ‘Cashew’));
// 7
// Example 2
console.log(FruitsArr);
// [ “Pineapple”, “Cashew”, “Orange”, “Banana”, “Pear”, “Mango”, “Pawpaw” ]
// Example 3
const numAr = [3, -9, 45, 100, -5, -35,-50, -19, -15];
console.log(numAr.unshift(‘me’));
// 10
console.log(numAr);
// [ “me”, 3, -9, 45, 100, -5, -35, -50, -19, -15 ]
// [].sort() Method
// Sort method dwells on Array of numbers and compareFn function. ((a: number, b: number) => number) | undefined): number[]
// It sorts an array in place. This method mutates the array and returns a reference to the same array.
// Its parameter is a function, which is used to determine the order of the elements. [].sort() Method returns a negative value if the first argument is less than the second argument, zero if they’re equal, and a positive value otherwise. If omitted, the elements are sorted in ascending, ASCII character order.
// Example 1
console.log([107,11,2,22,1,0].sort((a, b) => a — b));
// [0, 1, 2, 11, 22, 107]
// Example 2
const agez = [33, 16, 5, 54, 12, 21, 44, 20, 61, 13, 15, 45, 25, 64, 32];
const sortAges = agez.sort((a, b) => a — b);
console.log(sortAges);
// [5, 12, 13, 15, 16, 20, 21, 25, 32, 33, 34, 44, 45, 54, 61, 64]
// [].concat() Method
// (method) Array<string | number>.concat(…items: ConcatArray<string | number>[]): (string | number)[] (+1 overload)
// Combines two or more arrays. This method returns a new array without modifying any existing arrays.
// Its parameter are items — Additional arrays and/or items to add to the end of the array.
// Example 1
let concatString1 = ‘a’.concat(‘b’);
console.log(concatString1);
// Example 2
let concatString2 = ‘a’.concat([‘b’]);
console.log(concatString2);
// Example 3
let concatString3 = [‘a’].concat(‘b’).concat([‘mine’, [‘i’, ‘me’]]);
console.log(concatString3);
// Example 4
let concatString4 = ‘a’.concat([‘b’]).concat([‘mine’]);
console.log(concatString4);
// Example 5
let concatNumber1 = ‘7’.concat(-3);
console.log(concatNumber1);
// Example 6
let concatNumber2 = ‘7’.concat(‘5’);
console.log(concatNumber2);
// Example 7
let myNumber = [15];
let concatNumber3 = myNumber.concat(45);
console.log(concatNumber3);
// Example 8
let myNum = 15;
let concatNumber4 = myNum.concat(45);
console.log(concatNumber4);
// Uncaught TypeError: myNum.concat is not a function
// Example 9
let concatItems1 = ‘a’.concat(‘b’);
console.log(concatItems1);
// Example 10
let concatItems2 = ‘a’.concat(‘b’);
console.log(concatItems2);
// Example 11
var nums1 = [0, ‘1’, 2];
var nums2 = [3, 4];
var nums3 = [5, 6, 7];
var nums4 = [8]
var numsConcat = nums1.concat(nums2).concat(nums3).concat(nums4);
console.log(numsConcat);
// [ 0, “1”, 2, 3, 4, 5, 6, 7, 8 ]
// Example 12
let city1 = [‘Lagos’, ‘Ikeja’, ‘Oshodi’, ‘Mushin’];
let city2 = [‘London’, ‘Oxford’, ‘New York’];
const city3 = city1.concat(city2);
console.log(city3);
// Example 13
const mixMasala = [1, 0, ‘Egwusi’, ‘some soup’]
const me = [‘i’, [‘my’, ‘mine’ [19, 6, 70]]]
const agesToCC1 = [‘dr’,’Achugwo’, 17];
const agesToCC2 = [8, ‘techLead’, [11, -12, agesToCC1]];
const concatArrays = mixMasala
.concat(me)
.concat(agesToCC2)
.concat([‘myArrays’]);
log(concatArrays);
// [ 1, 0, “Egwusi”, “some soup”, “i”, [‘my’, ‘mine’ [19, 6, 70]], 8, “techLead”, [11, -12, [‘dr’,’Achugwo’, 17]], “myArrays” ]
// [].find() Method
// find returns the value of the first element in the array where predicate is true, and undefined otherwise.
// Its parameter is a predicate
// find calls predicate once for each element of the array, in ascending order, until it finds one where predicate returns true. If such an element is found, find immediately returns that element value. Otherwise, find returns undefined.
// Its parameter is a thisArg
// If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.
// Example 1
const xComp1 = companies.find(company => company.name == ‘Shoprite’);
log(xComp1);
// Example 2
console.log(companies.find(chi => chi.name === “GSAP”));
// Example 3
console.log(companies.find(gDate => (gDate.end — gDate.start >= 18))); Object { name: “Ford Motors”, category: “Auto”, start: “1999”, end: “2007” }
// Example 4
console.log(companies.find(gDate => (gDate.end — gDate.start > 8)));
// Object { name: “Nova Investment”, category: “Finance”, start: “1980”, end: “2003” }
// Example 5
console.log(companies.find(gDate => (gDate.end — gDate.start < 8)));
// Object { name: “PedroTech”, category: “Technology”, start: “2009”, end: “2014” }
领英推荐
// Example 6
console.log(companies.find(gDate => (gDate.end — gDate.start === 8)));
// Object { name: “Ford Motors”, category: “Auto”, start: “1999”, end: “2007” }
// Example 7
const xComp2 = companies.find(company => company.category == ‘Finance’);
log(xComp2);
// Object { name: “Nova Investment”, category: “Finance”, start: “1980”, end: “2003” }
// Example 8
const xComp2b = companies.find(comp => comp.category == ‘Film’);
log(xComp2b);
// undefined
// Example 9
const xComp3 = companies.find(company => company.start == 2009);
log(xComp3);
// [].findIndex() Method
// (method) Array<never>.findIndex(predicate: (value: never, index: number, obj: never[]) => unknown, thisArg?: any): number
// Returns the index of the first element in the array where predicate is true, and -1 otherwise.
// @param predicate
// find calls predicate once for each element of the array, in ascending order, until it finds one where predicate returns true. If such an element is found, findIndex immediately returns that element index. Otherwise, findIndex returns -1.
// @param thisArg
// If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.
// Example 1
const xComp4 = companies.findIndex(company => company.name == ‘PedroTech’);
log(xComp4);
// [].every() Method
// (method) Array<never>.every<never>(predicate: (value: never, index: number, array: never[]) => value is never, thisArg?: any): this is never[] (+1 overload)
// Determines whether all the members of an array satisfy the specified test.
// @param predicate
// A function that accepts up to three arguments. The every method calls the predicate function for each element in the array until the predicate returns a value which is coercible to the Boolean value false, or until the end of the array.
// @param thisArg
// An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.
// Example 1 — is Every Company name NOT ‘me’ ?
const booleanCo1 = companies.every(comp => comp.name != ‘me’);
log(booleanCo1);
//true
// Example 2 — is the name of Every Company ‘Shoprite’ ?
const booleanCo2 = companies.every(comp => comp.name == ‘Shoprite’);
console.log(booleanCo2);
// false
// Example 3 — is the category of Every Company ‘Shoprite’ ?
const booleanCo3 = companies.every(comp => comp.category == ‘Shoprite’);
console.log(booleanCo3);
// false
// Example 4 — is the category of Every Company NOT ‘Shoprite’ ?
const booleanCo4 = companies.every(comp => comp.category != ‘Shoprite’);
console.log(booleanCo4);
// true
// Example 5 — the year Every Company started ? 1980 : after 1980
const booleanCo5 = companies.every(comp => comp.start >= 1980);
console.log(booleanCo5);
// true
// Example 6 — the year Every Company ended
const booleanCo6 = companies.every(comp => comp.end <= 2016);
console.log(booleanCo6);
// true
// Example 7 — years Every Company lasted
const booleanCo7 = companies.every(comp => (comp.end — comp.start) >= 5);
console.log(booleanCo7);
// false
// Example 8 — years Every Company lasted
const booleanCo8 = companies.every(comp => (comp.end — comp.start) <= 10);
console.log(booleanCo8);
// true
// Example 9 — years Every Company lasted
const booleanCo9 = companies.every(comp => (comp.end — comp.start) > 4);
console.log(booleanCo9);
// true
// [].some() Method
// (method) Array<never>.some(predicate: (value: never, index: number, array: never[]) => unknown, thisArg?: any): boolean
// Determines whether the specified callback function returns true for any element of an array.
// @param predicate
// A function that accepts up to three arguments. The some method calls the predicate function for each element in the array until the predicate returns a value which is coercible to the Boolean value true, or until the end of the array.
// @param thisArg
// An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.
// Example 1 — are Some Companies name NOT ‘me’ ?
const booleanCo1 = companies.some(comp => comp.name != ‘Retail’);
log(booleanCo1);
// true
// Example 2 — is the name of Some Companies ‘Shoprite’ ?
const booleanCo2 = companies.some(comp => comp.name == ‘Shoprite’);
console.log(booleanCo2);
// true
// Example 3 — is the category of Some Companies ‘Shoprite’ ?
const booleanCo3 = companies.some(comp => comp.category == ‘PedroTech’);
console.log(booleanCo3);
// false
// Example 4 — is the category of Some Companies NOT ‘Shoprite’ ?
const booleanCo4 = companies.some(comp => comp.category != ‘Shoprite’);
console.log(booleanCo4);
// true
// Example 5 — the year Some Companies started ? 2010 : after 1980
const booleanCo5 = companies.some(comp => comp.start >= 2013);
console.log(booleanCo5);
// false
// Example 6 — the year Some Companies ended
const booleanCo6 = companies.some(comp => comp.end <= 2016);
console.log(booleanCo6);
// true
Example 7 — years Some Companies lasted
const booleanCo7 = companies.some(comp => (comp.end — comp.start) >= 27);
console.log(booleanCo7);
// false
Example 8 — years Some Companies lasted
const booleanCo8 = companies.some(comp => (comp.end — comp.start) <= 10);
console.log(booleanCo8);
// true
Example 9 — years Some Companies lasted
const booleanCo9 = companies.some(comp => (comp.end — comp.start) > 4);
console.log(booleanCo9);
// true
// [].entries() Method
// (method) Array<string | number>.entries(): IterableIterator<[number, string | number]>
// Returns an iterable of key, value pairs for every entry in the array.
// In other words, the entries() method returns a new array iterator object that contains the key/value pairs for each index in the array.
Example 1
const array1 = [‘a’, ‘b’, ‘c’];
const iterator1 = array1.entries();
console.log(iterator1.next().value);
// [0, “a”]
// Example 2
console.log(iterator1.next().value);
// [1, “b”]
// [].copyWithin() Method
(method) Array<string | number>.copyWithin(target: number, start?: number | undefined, end?: number | undefined): (string | number)[]
// Returns the this object after copying a section of the array identified by start and end to the same array starting at position target
// @param target
// If target is negative, it is treated as length+target where length is the length of the array.
// @param start
// If start is negative, it is treated as length+start. If end is negative, it is treated as length+end. If start is omitted, 0 is used.
// Example 1
const array1 = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’];
// Copy to index 0 the element at index 3
console.log(array1.copyWithin(0, 3, 4));
// [“d”, “b”, “c”, “d”, “e”]
// Example 2
// Copy to index 1 all elements from index 3 to the end
console.log(array1.copyWithin(1, 3));
// [“d”, “d”, “e”, “d”, “e”]
// Example 3
const fruits = [“Banana”, 12, “Orange”, “Apple”, “Man”, “go”, “Pear”, “Pum”, “kin”, “Ube”];
console.log(fruits.copyWithin(1, 3, 7));
// [ “Banana”, “Apple”, “Man”, “go”, “Pear”, “go”, “Pear”, “Pum”, “kin”, “Ube” ]
// [].fill() Method
// (method) Array<number>.fill(value: number, start?: number | undefined, end?: number | undefined): number[]
// Changes all array elements from start to end index to a static value and returns the modified array
// @param value — value to fill array section with
// @param start
// index to start filling the array at. If start is negative, it is treated as length+start where length is the length of the array.
// @param end
// index to stop filling the array at. If end is negative, it is treated as length+end.
// (method) Array<never>.fill(value: never, start?: number | undefined, end?: number | undefined): never[]
// Example 1
const array1 = [1, 2, 3, 4];
// Fill with 0 from position 2 until position 4
console.log(array1.fill(0, 2, 4));
// [1, 2, 0, 0]
// Example 2
// Fill with 5 from position 1
console.log(array1.fill(5, 1));
// [1, 5, 5, 5]
// Example 3
console.log(array1.fill(6));
// [6, 6, 6, 6]
// [].includes() Method
// Example 1
const myObj = companies[1];
const incluObj1 = companies.includes(myObj);
console.log(incluObj1);
// true
// Example 2
const incluObj2 = companies.includes(companies[4]);
console.log(incluObj2);
// true
// Example 3
console.log(companies.includes(companies[7]));
// true
// Example 4
console.log(companies.includes(companies[17]));
// false
// Example 5
const numAr1 = [3, -9, 45, 100, -5, -35, -50, -19, -15, -32, -25];
const incluNum = numAr1.includes(-15);
console.log(incluNum);
// true
// Example 6
console.log(numAr1.includes(78));
// false
// Example 7
console.log(numAr1.includes(25));
// false
// Example 8
console.log(numAr1.includes(3));
// true
// [].keys() Method
// (method) Array<never>.keys(): IterableIterator<number>
// Returns an iterable of keys in the array.
// Example 1
const array1 = [‘a’, ‘b’, ‘c’];
const iterator = array1.keys();
for (const key of iterator) {
console.log(key);
}
// 0
// 1
// 2
// Example 2
<h1>JavaScript Objects</h1>
<h2>The Object.keys() Method</h2>
<p>Object.keys() returns an Array Iterator object with the keys of an object:</p>
<p id=”demo”></p>
<script>
const fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
const keys = Object.keys(fruits);
let text = “”;
for (let x of keys) {
text += x + “<br>”;
}
document.getElementById(“demo”).innerHTML = text;
</script>
<p>Object.keys() is not supported in Internet Explorer 11 (or earlier).</p>
</body>
</html>
Object.keys() returns an Array Iterator object with the keys of an object:
0
1
2
3
Object.keys() is not supported in Internet Explorer 11 (or earlier).
// [].pop() Method
// (method) Array<never>.pop(): undefined
// Removes the last element from an array and returns it. If the array is empty, undefined is returned and the array is not modified.
// Example 1
const numAr = [3, -9, 45, 100, -5, -35,-50, -19, -15, -32, -25];
console.log(numAr.pop());
// -25
// [].slice() Method
// (method) Array<string | number>.slice(start?: number | undefined, end?: number | undefined): (string | number)[]
// Returns a copy of a section of an array. For both start and end, a negative index can be used to indicate an offset from the end of the array. For example, -2 refers to the second to last element of the array.
// @param start
// The beginning index of the specified portion of the array. If start is undefined, then the slice begins at index 0.
// @param end
// The end index of the specified portion of the array. This is exclusive of the element at the index ‘end’. If end is undefined, then the slice extends to the end of the array.
// Example 1
let obiMe = [‘Ik’, ‘K’, ‘Orange’, 6, ‘Yellow’, 17, ‘now’];
console.log(obiMe.slice(1, 5));
// [“K”, “Orange”, 6, “Yellow”]
// [].splice() Method
// (method) Array<number>.splice(start: number, deleteCount?: number | undefined): number[] (+1 overload)
// Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.
// @param start — The zero-based location in the array from which to start removing elements.
// @param deleteCount — The number of elements to remove.
// @returns — An array containing the elements that were deleted
// Example 1
const numAr = [3, -19, 45, 107, -5, 35, -50, 9, -15, -32, -25];
console.log(numAr.splice(3));
// [ 107, -5, 35, -50, 9, -15, -32, -25 ]
// [].toString() Method
// (method) Array<number>.toString(): string
// Returns a string representation of an array.
const numAr = [3, -9, 45, 100, -5, -35, -15, -32, -25];
console.log(numAr.toString()); 3,-9,45,100,-5,-35,-15,-32,-25
// [].shift() Method
// (method) Array<string | number>.shift(): string | number | undefined
// Removes the first element from an array and returns it. If the array is empty, undefined is returned and the array is not modified.
const numAr = [3, -9, 45, 100, -5, -35, -50, -19, -15, -32, -25];
console.log(numAr.shift()); 3
const emptyAr = [];
console.log(emptyAr.shift()); undefined
const someNames = [‘Jimmy’, ‘Toby’, ‘Okey’, 4, ‘Nna’, ‘Oby’];
console.log(someNames.shift()); Jimmy
// [].unshift() Method
// (method) Array<string | number>.unshift(…items: (string | number)[]): number
// Inserts new elements at the start of an array, and returns the new length of the array.
// Its parameter is a items — Elements to insert at the start of the array.
// Example 1
const FruitsArr = [‘Orange’, ‘Banana’, ‘Pear’, ‘Mango’, ‘Pawpaw’];
console.log(FruitsArr.unshift(‘Pineapple’, ‘Cashew’));
// 7
// Example 2
console.log(FruitsArr);
// [ “Pineapple”, “Cashew”, “Orange”, “Banana”, “Pear”, “Mango”, “Pawpaw” ]
// Example 3
const numAr = [3, -9, 45, 100, -5, -35,-50, -19, -15];
console.log(numAr.unshift(‘me’));
// 10
// Example 4
console.log(numAr);
// [“me”, 3, -9, 45, 100, -5, -35, -50, -19, -15]
// (method) Array<string | number>.push(…items: (string | number)[]): number
// Appends new elements to the end of an array, and returns the new length of the array.
// Its parameter is array items — New elements to add to the array.
// Example 5 — push() Method with an array of numbers and strings
const child = [‘Baby’, 0, ‘kid’, ‘children’, ‘kindergaten’];
console.log(child.push(‘underage’, ‘minor’, 4));
// 8
// Example 6
console.log(child);
// [ “Baby”, 0, “kid”, “children”, “kindergaten”, “underage”, “minor”, 4 ]
// [].values() Method
// (method) Array<never>.values(): IterableIterator<never>
// Returns an iterable of values in the array
// Example 1
const array1 = [‘a’, ‘b’, ‘c’];
const iterator = array1.values();
for (const value of iterator) {
console.log(value);
}
// “a”
// “b”
// “c”
// Example 2
const numAr = [3, -9, 45, 100, -5, -35, 50, -19];
const iterator = numAr.values();
for (const value of iterator) {
console.log(value);
}
// 3
-9
45
100
-5
-35
50
-19
Summary
JavaScript Array length
Returns the number of elements in an array
JavaScript Array reverse()
Returns the array in reverse order
JavaScript Array sort()
Sorts the elements of an array in specific order
JavaScript Array fill()
Returns array by filling elements with given value
Javascript Array join()
Concatenates the array elements to a string
Javascript Array toString()
Returns the string representation of an array
JavaScript Array pop()
Removes and returns the last array element
JavaScript Array shift()
Removes and returns the first array element
JavaScript Array push()
Adds elements to end of array & returns its length
JavaScript Array unshift()
Adds elements to start of array and returns length
JavaScript Array concat()
Returns array by merging given value and/or arrays
JavaScript Array splice()
Returns an array by changing its elements in place
JavaScript Array lastIndexOf()
Returns the last index of occurrence of an element
JavaScript Array indexOf()
Returns the first index of occurrence of element
JavaScript Array of() Method
Creates a new Array instance from given arguments
JavaScript Array slice()
Returns a shallow copy of a portion of an array
JavaScript Array findIndex()
Returns index of element that satisfies condition
JavaScript Array find()
Returns first element that satisfies a condition
JavaScript Array includes()
Checks if a value exists in an array
Javascript Array reduceRight()
Reduces array to single value from right to left
Javascript Array reduce()
Reduces array to single value from left to right
Javascript Array isArray()
Checks if the given value is a JavaScript Array
Javascript Array filter()
Returns array by filtering elements on given test
JavaScript Array map()
Returns array by mapping elements using given func
Javascript Array forEach()
Executes the given function on array elements
Javascript Array some()
Tests if any element passes given test function
JavaScript Array every()
Tests if all elements pass the given test function
Javascript Array entries()
Returns iterator containing key/value pair array
JavaScript Array keys()
Returns an iterator containing keys of array items
JavaScript Array values()
Returns iterator containing values of array items
Javascript Array.from()
Creates a new Array from array-like object
Javascript Array constructor
Returns the constructor function for the array
Javascript Array copyWithin()
Copies and overwrites elements within the array
JavaScript Array toLocaleString()
Returns string representing the elements of array
JavaScript Array flat()
Flattens the nested array to given depth
JavaScript Array flatMap()
Returns new array by mapping and flattening array