SlideShare a Scribd company logo
What are Arrays in JavaScript?
Before we proceed, you need to understand what arrays really mean.
In JavaScript,anarray is a variable that is used to store different data types.
It basically stores different elements in one box and canbe later assesssed
with the variable.
Declaring an array:
let myBox = []; // Initial Arraydeclaration in JS
Arrays can contain multiple data types
let myBox = ['hello', 1, 2, 3, true, 'hi'];
Arrays can be manipulated by using several actions known
as methods. Some of these methods allow us to add, remove, modify
and do lots more to arrays.
I would be showing you a few in this article, let’s roll :)
NB: I used Arrow functions in this post, If you don’t know what this means,
you should read here. Arrow function is an ES6 feature.
toString()
The JavaScript method toString() converts an array to a string
separated by a comma.
let colors = ['green', 'yellow', 'blue'];
console.log(colors.toString()); // green,yellow,blue
join()
The JavaScript join() method combines all array elements into a string.
It is similar to toString() method, but here you can specify the
separator instead of the default comma.
let colors = ['green', 'yellow', 'blue'];
console.log(colors.join('-')); // green-yellow-blue
concat
This method combines two arrays together or add more items to an
array and then return a new array.
let firstNumbers = [1, 2, 3];
let secondNumbers = [4, 5, 6];
let merged = firstNumbers.concat(secondNumbers);
console.log(merged); // [1, 2, 3, 4, 5, 6]
push()
This method adds items to the end of an array and changes the original
array.
let browsers = ['chrome', 'firefox', 'edge'];
browsers.push('safari', 'opera mini');
console.log(browsers);
// ["chrome", "firefox", "edge", "safari", "opera mini"]
pop()
This method removes the last item of an array and returns it.
let browsers = ['chrome', 'firefox', 'edge'];
browsers.pop(); // "edge"
console.log(browsers); // ["chrome", "firefox"]
shift()
This method removes the first item of an array and returns it.
let browsers = ['chrome', 'firefox', 'edge'];
browsers.shift(); // "chrome"
console.log(browsers); // ["firefox", "edge"]
unshift()
This method adds an item(s) to the beginning of an array
and changes the original array.
let browsers = ['chrome', 'firefox', 'edge'];
browsers.unshift('safari');
console.log(browsers); // ["safari", "chrome", "firefox", "edge"]
You can also add multipleitems at once
splice()
This method changes an array, by adding, removing and inserting
elements.
The syntax is:
array.splice(index[, deleteCount, element1, ..., elementN])
 Index here is the starting point for removing elements in the array
 deleteCount is the number of elements to be deleted from that index
 element1, …, elementN is the element(s) to be added
Removing items
after running splice() , it returns the array with the item(s) removed and
removes it from the original array.
let colors = ['green', 'yellow', 'blue', 'purple'];
colors.splice(0, 3);
console.log(colors); // ["purple"]
// deletes ["green", "yellow", "blue"]
NB: The deleteCount does not includethe last index in range.
If the second parameter is not declared, every element starting from the
given index will be removed from the array:
let colors = ['green', 'yellow', 'blue', 'purple'];
colors.splice(3);
console.log(colors); // ["green", "yellow", "blue"]
// deletes ['purple']
In the next example we will remove 3 elements from the array and
replace them with more items:
let schedule = ['I', 'have', 'a', 'meeting', 'tommorrow'];
// removes 4 first elements and replace them with another
schedule.splice(0, 4, 'we', 'are', 'going', 'to', 'swim');
console.log(schedule);
// ["we", "are", "going", "to", "swim", "tommorrow"]
Addingitems
To add items, we need to set the deleteCount to zero
let schedule = ['I', 'have', 'a', 'meeting', 'with'];
// adds 3 new elements to the array
schedule.splice(5, 0, 'some', 'clients', 'tommorrow');
console.log(schedule);
// ["I", "have", "a", "meeting", "with", "some", "clients", "tommorrow"]
slice()
This method is similar to splice() but very different. It returns subarrays
instead of substrings.
This method copies a given part of an array and returns that copied
part as a new array. It does not change the original array.
The syntax is:
array.slice(start, end)
Here’s a basic example:
let numbers = [1, 2, 3, 4]
numbers.slice(0, 3)
// returns [1, 2, 3]
console.log(numbers) // returns the original array
The best way to use slice() is to assign it to a new variable.
let message = 'congratulations'
const abbrv = message.slice(0, 7) + 's!';
console.log(abbrv) // returns "congrats!"
split()
This method is used for strings. It divides a string into substrings and
returns them as an array.
Here’s the syntax:string.split(separator, limit);
 The separator here defines how to split a string either by a comma.
 The limit determines the number of splits to be carried out
let firstName = 'Bolaji';
// return the string as an array
firstName.split() // ["Bolaji"]
another example:
let firstName = 'hello, my name is bolaji, I am a dev.';
firstName.split(',', 2); // ["hello", " my name is bolaji"]
NB: If we declare an empty array, like this firstName.split(''); then each item in
the string will be divided as substrings:
let firstName = 'Bolaji';
firstName.split('') // ["B", "o", "l", "a", "j", "i"]
indexOf()
This method looks for an item in an array and returns the index where
it was found else it returns -1
let fruits = ['apple', 'orange', false, 3]
fruits.indexOf('orange'); // returns 1
fruits.indexOf(3); // returns 3
friuts.indexOf(null); // returns -1 (not found)
lastIndexOf()
This method works the same way indexOf() does except that it works
from right to left. It returns the last index where the item was found
let fruits = ['apple', 'orange', false, 3, 'apple']
fruits.lastIndexOf('apple'); // returns 4
filter()
This method creates a new array if the items of an array pass a certain
condition.
The syntax is:
let results = array.filter(function(item, index, array) {
// returns true if the item passes the filter
});
Example:
Checks users from Nigeria
const countryCode = ['+234', '+144', '+233', '+234'];
const nigerian = countryCode.filter( code => code === '+234');
console.log(nigerian); // ["+234", "+234"]
map()
This method creates a new array by manipulating the values in an array.
Example:
Displays usernames on a page. (Basic friend list display)
const userNames = ['tina', 'danny', 'mark', 'bolaji'];
const display = userNames.map(item => {
return '<li>' + item + '</li>';
})
const render = '<ul>' + display.join('') + '</ul>';
document.write(render);
another example:
// adds dollar sign to numbers
const numbers = [10, 3, 4, 6];
const dollars = numbers.map( number => '$' + number);
console.log(dollars);
// ['$10', '$3', '$4', '$6'];
reduce()
This method is good for calculating totals.
reduce() is used to calculate a single value based on an array.
let value = array.reduce(function(previousValue, item, index, array) {
// ...
}, initial);
example:
To loop through an array and sum all numbers in the array up, we can use
the for of loop.
const numbers = [100, 300, 500, 70];
let sum = 0;
for (let n of numbers) {
sum += n;
}
console.log(sum);
Here’s how to do same with reduce()
const numbers = [100, 300, 500, 70];
const sum = numbers.reduce((accummulator, value) =>
accummulator + value
, 0);
console.log(sum); // 970
If you omit the initialvalue, the total will by default start from the first item
in the array.
const numbers = [100, 300, 500, 70];
const sum = numbers.reduce((accummulator, value) => accummulator + value);
console.log(sum); // still returns 970
The snippet below shows how the reduce() method works with all four
arguments.
More insights into the reduce() method and various ways of using it
can be found here and here.
forEach()
This method is good for iterating through an array.
It applies a function on all items in an array
const colors = ['green', 'yellow', 'blue'];
colors.forEach((item, index) => console.log(index, item));
// returns the index and the every item in the array
// 0 "green"
// 1 "yellow"
// 2 "blue"
iteration can be done without passing the index argument
const colors = ['green', 'yellow', 'blue'];
colors.forEach((item) => console.log(item));
// returns everyitem in the array
// "green"
// "yellow"
// "blue"
every()
This method checks if all items in an array pass the specified condition
and returntrue if passed, else false.
check if all numbers are positive
const numbers = [1, -1, 2, 3];
let allPositive = numbers.every((value) => {
return value >= 0;
})
console.log(allPositive); // would return false
some()
This method checks if an item (one or more) in an array pass the
specified condition and return true if passed, else false.
checks if at least one number is positive
const numbers = [1, -1, 2, 3];
let atLeastOnePositive = numbers.some((value) => {
return value >= 0;
})
console.log(atLeastOnePositive); // would return true
includes()
This method checks if an array contains a certain item. It is similar
to .some(), but instead of looking for a specific condition to pass, it
checks if the array contains a specific item.
let users = ['paddy', 'zaddy', 'faddy', 'baddy'];
users.includes('baddy'); // returns true
If the item is not found, it returns false
Summary
toString() converts an array to a string separated by a comma.
join() combines all array elements into a string.
concat combines two arrays together or add more items to an array and then return a new array.
push() adds item(s) to the end of an array and changes the original array.
pop() removes the last item of an array and returns it
shift() removes the first item of an array and returns it
unshift() adds an item(s) to the beginning of an array and changes the original array.
splice() changes an array, by adding, removing and inserting elements.
slice() copies a given part of an array and returns that copied part as a new array. It does not change the
original array.
split() divides a string into substrings and returns them as an array.
indexOf() looks for an item in an array and returns the index where it was found else it returns -1
lastIndexOf() looks for an item from right to left and returns the last index where the item was found.
filter() creates a new array if the items of an array pass a certain condition.
map() creates a new array by manipulating the values in an array.
reduce() calculates a single value based on an array.
forEach() iterates through an array, it applies a function on all items in an array
every() checks if all items in an array pass the specified condition and return true if passed, else false.
some() checks if an item (one or more) in an array pass the specified condition and return true if passed,
else false.
includes() checks if an array contains a certain item.

More Related Content

What's hot (19)

Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기
진성 오
 
Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) DataCategory theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Data
greenwop
 
Collections Framework
Collections FrameworkCollections Framework
Collections Framework
Sunil OS
 
Google collections api an introduction
Google collections api   an introductionGoogle collections api   an introduction
Google collections api an introduction
gosain20
 
Programmation fonctionnelle en JavaScript
Programmation fonctionnelle en JavaScriptProgrammation fonctionnelle en JavaScript
Programmation fonctionnelle en JavaScript
Loïc Knuchel
 
関数潮流(Function Tendency)
関数潮流(Function Tendency)関数潮流(Function Tendency)
関数潮流(Function Tendency)
riue
 
Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)
stasimus
 
Chaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscoreChaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscore
Nicolas Carlo
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean Code
Ganesh Samarthyam
 
Martin Fowler's Refactoring Techniques Quick Reference
Martin Fowler's Refactoring Techniques Quick ReferenceMartin Fowler's Refactoring Techniques Quick Reference
Martin Fowler's Refactoring Techniques Quick Reference
Seung-Bum Lee
 
MCE^3 - Hannes Verlinde - Let The Symbols Do The Work
MCE^3 - Hannes Verlinde - Let The Symbols Do The WorkMCE^3 - Hannes Verlinde - Let The Symbols Do The Work
MCE^3 - Hannes Verlinde - Let The Symbols Do The Work
PROIDEA
 
Stuff you didn't know about action script
Stuff you didn't know about action scriptStuff you didn't know about action script
Stuff you didn't know about action script
Christophe Herreman
 
Swift internals
Swift internalsSwift internals
Swift internals
Jung Kim
 
SDC - Einführung in Scala
SDC - Einführung in ScalaSDC - Einführung in Scala
SDC - Einführung in Scala
Christian Baranowski
 
7 Habits For a More Functional Swift
7 Habits For a More Functional Swift7 Habits For a More Functional Swift
7 Habits For a More Functional Swift
Jason Larsen
 
Java Cheat Sheet
Java Cheat SheetJava Cheat Sheet
Java Cheat Sheet
Saeid Zebardast
 
JavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashJavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and Lodash
Bret Little
 
Extractors & Implicit conversions
Extractors & Implicit conversionsExtractors & Implicit conversions
Extractors & Implicit conversions
Knoldus Inc.
 
Introduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in HaskellIntroduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in Haskell
nebuta
 
Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기
진성 오
 
Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) DataCategory theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Data
greenwop
 
Collections Framework
Collections FrameworkCollections Framework
Collections Framework
Sunil OS
 
Google collections api an introduction
Google collections api   an introductionGoogle collections api   an introduction
Google collections api an introduction
gosain20
 
Programmation fonctionnelle en JavaScript
Programmation fonctionnelle en JavaScriptProgrammation fonctionnelle en JavaScript
Programmation fonctionnelle en JavaScript
Loïc Knuchel
 
関数潮流(Function Tendency)
関数潮流(Function Tendency)関数潮流(Function Tendency)
関数潮流(Function Tendency)
riue
 
Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)
stasimus
 
Chaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscoreChaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscore
Nicolas Carlo
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean Code
Ganesh Samarthyam
 
Martin Fowler's Refactoring Techniques Quick Reference
Martin Fowler's Refactoring Techniques Quick ReferenceMartin Fowler's Refactoring Techniques Quick Reference
Martin Fowler's Refactoring Techniques Quick Reference
Seung-Bum Lee
 
MCE^3 - Hannes Verlinde - Let The Symbols Do The Work
MCE^3 - Hannes Verlinde - Let The Symbols Do The WorkMCE^3 - Hannes Verlinde - Let The Symbols Do The Work
MCE^3 - Hannes Verlinde - Let The Symbols Do The Work
PROIDEA
 
Stuff you didn't know about action script
Stuff you didn't know about action scriptStuff you didn't know about action script
Stuff you didn't know about action script
Christophe Herreman
 
Swift internals
Swift internalsSwift internals
Swift internals
Jung Kim
 
7 Habits For a More Functional Swift
7 Habits For a More Functional Swift7 Habits For a More Functional Swift
7 Habits For a More Functional Swift
Jason Larsen
 
JavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashJavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and Lodash
Bret Little
 
Extractors & Implicit conversions
Extractors & Implicit conversionsExtractors & Implicit conversions
Extractors & Implicit conversions
Knoldus Inc.
 
Introduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in HaskellIntroduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in Haskell
nebuta
 

Similar to What are arrays in java script (20)

javascript-Array.ppsx
javascript-Array.ppsxjavascript-Array.ppsx
javascript-Array.ppsx
VedantSaraf9
 
PHP Array very Easy Demo
PHP Array very Easy DemoPHP Array very Easy Demo
PHP Array very Easy Demo
Salman Memon
 
JavaScript Array Interview Questions PDF By ScholarHat
JavaScript Array Interview Questions PDF By ScholarHatJavaScript Array Interview Questions PDF By ScholarHat
JavaScript Array Interview Questions PDF By ScholarHat
Scholarhat
 
Java script arrays
Java script arraysJava script arrays
Java script arrays
Frayosh Wadia
 
Java script array methods
Java script array methodsJava script array methods
Java script array methods
chauhankapil
 
8558537werr.pptx
8558537werr.pptx8558537werr.pptx
8558537werr.pptx
ssuser8a9aac
 
Learn java script
Learn java scriptLearn java script
Learn java script
Mahmoud Asadi
 
Ms Ajax Array Extensions
Ms Ajax Array ExtensionsMs Ajax Array Extensions
Ms Ajax Array Extensions
jason hu 金良胡
 
JavaScript.pptx
JavaScript.pptxJavaScript.pptx
JavaScript.pptx
pramod599939
 
Java script advance-auroskills (2)
Java script advance-auroskills (2)Java script advance-auroskills (2)
Java script advance-auroskills (2)
BoneyGawande
 
Intro to React
Intro to ReactIntro to React
Intro to React
Troy Miles
 
ECMA5 and ES6 Promises
ECMA5 and ES6 PromisesECMA5 and ES6 Promises
ECMA5 and ES6 Promises
Oswald Campesato
 
Underscore.js
Underscore.jsUnderscore.js
Underscore.js
timourian
 
GDI Seattle - Intro to JavaScript Class 2
GDI Seattle - Intro to JavaScript Class 2GDI Seattle - Intro to JavaScript Class 2
GDI Seattle - Intro to JavaScript Class 2
Heather Rock
 
React Native Evening
React Native EveningReact Native Evening
React Native Evening
Troy Miles
 
1-JAVA SCRIPT. servere-side applications vs client side applications
1-JAVA SCRIPT. servere-side applications vs client side applications1-JAVA SCRIPT. servere-side applications vs client side applications
1-JAVA SCRIPT. servere-side applications vs client side applications
surajshreyans
 
Java script
Java scriptJava script
Java script
Adrian Caetano
 
Working with Arrays in JavaScript
Working with Arrays in JavaScriptWorking with Arrays in JavaScript
Working with Arrays in JavaScript
Florence Davis
 
The hidden and new parts of JS
The hidden and new parts of JSThe hidden and new parts of JS
The hidden and new parts of JS
Ritesh Kumar
 
Js objects
Js objectsJs objects
Js objects
Charles Russell
 
javascript-Array.ppsx
javascript-Array.ppsxjavascript-Array.ppsx
javascript-Array.ppsx
VedantSaraf9
 
PHP Array very Easy Demo
PHP Array very Easy DemoPHP Array very Easy Demo
PHP Array very Easy Demo
Salman Memon
 
JavaScript Array Interview Questions PDF By ScholarHat
JavaScript Array Interview Questions PDF By ScholarHatJavaScript Array Interview Questions PDF By ScholarHat
JavaScript Array Interview Questions PDF By ScholarHat
Scholarhat
 
Java script array methods
Java script array methodsJava script array methods
Java script array methods
chauhankapil
 
Java script advance-auroskills (2)
Java script advance-auroskills (2)Java script advance-auroskills (2)
Java script advance-auroskills (2)
BoneyGawande
 
Intro to React
Intro to ReactIntro to React
Intro to React
Troy Miles
 
Underscore.js
Underscore.jsUnderscore.js
Underscore.js
timourian
 
GDI Seattle - Intro to JavaScript Class 2
GDI Seattle - Intro to JavaScript Class 2GDI Seattle - Intro to JavaScript Class 2
GDI Seattle - Intro to JavaScript Class 2
Heather Rock
 
React Native Evening
React Native EveningReact Native Evening
React Native Evening
Troy Miles
 
1-JAVA SCRIPT. servere-side applications vs client side applications
1-JAVA SCRIPT. servere-side applications vs client side applications1-JAVA SCRIPT. servere-side applications vs client side applications
1-JAVA SCRIPT. servere-side applications vs client side applications
surajshreyans
 
Working with Arrays in JavaScript
Working with Arrays in JavaScriptWorking with Arrays in JavaScript
Working with Arrays in JavaScript
Florence Davis
 
The hidden and new parts of JS
The hidden and new parts of JSThe hidden and new parts of JS
The hidden and new parts of JS
Ritesh Kumar
 
Ad

Recently uploaded (20)

Code and No-Code Journeys: The Coverage Overlook
Code and No-Code Journeys: The Coverage OverlookCode and No-Code Journeys: The Coverage Overlook
Code and No-Code Journeys: The Coverage Overlook
Applitools
 
Generative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its ApplicationsGenerative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its Applications
SandeepKS52
 
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The SequelMarketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
BradBedford3
 
Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
Neuralink TemplateeeeeeeeeeeeeeeeeeeeeeeeeeNeuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
alexandernoetzold
 
AI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA TechnologiesAI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA Technologies
SandeepKS52
 
Maximizing Business Value with AWS Consulting Services.pdf
Maximizing Business Value with AWS Consulting Services.pdfMaximizing Business Value with AWS Consulting Services.pdf
Maximizing Business Value with AWS Consulting Services.pdf
Elena Mia
 
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps CyclesFrom Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
Marjukka Niinioja
 
Software Testing & it’s types (DevOps)
Software  Testing & it’s  types (DevOps)Software  Testing & it’s  types (DevOps)
Software Testing & it’s types (DevOps)
S Pranav (Deepu)
 
wAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptxwAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptx
SimonedeGijt
 
Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)
VICTOR MAESTRE RAMIREZ
 
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
WSO2
 
Top 5 Task Management Software to Boost Productivity in 2025
Top 5 Task Management Software to Boost Productivity in 2025Top 5 Task Management Software to Boost Productivity in 2025
Top 5 Task Management Software to Boost Productivity in 2025
Orangescrum
 
Best Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small BusinessesBest Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small Businesses
TheTelephony
 
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
Insurance Tech Services
 
GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?
felipeceotto
 
Leveraging Foundation Models to Infer Intents
Leveraging Foundation Models to Infer IntentsLeveraging Foundation Models to Infer Intents
Leveraging Foundation Models to Infer Intents
Keheliya Gallaba
 
14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework
Angelo Theodorou
 
Key AI Technologies Used by Indian Artificial Intelligence Companies
Key AI Technologies Used by Indian Artificial Intelligence CompaniesKey AI Technologies Used by Indian Artificial Intelligence Companies
Key AI Technologies Used by Indian Artificial Intelligence Companies
Mypcot Infotech
 
Porting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 WebinarPorting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 Webinar
ICS
 
Plooma is a writing platform to plan, write, and shape books your way
Plooma is a writing platform to plan, write, and shape books your wayPlooma is a writing platform to plan, write, and shape books your way
Plooma is a writing platform to plan, write, and shape books your way
Plooma
 
Code and No-Code Journeys: The Coverage Overlook
Code and No-Code Journeys: The Coverage OverlookCode and No-Code Journeys: The Coverage Overlook
Code and No-Code Journeys: The Coverage Overlook
Applitools
 
Generative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its ApplicationsGenerative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its Applications
SandeepKS52
 
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The SequelMarketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
BradBedford3
 
Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
Neuralink TemplateeeeeeeeeeeeeeeeeeeeeeeeeeNeuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
alexandernoetzold
 
AI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA TechnologiesAI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA Technologies
SandeepKS52
 
Maximizing Business Value with AWS Consulting Services.pdf
Maximizing Business Value with AWS Consulting Services.pdfMaximizing Business Value with AWS Consulting Services.pdf
Maximizing Business Value with AWS Consulting Services.pdf
Elena Mia
 
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps CyclesFrom Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
Marjukka Niinioja
 
Software Testing & it’s types (DevOps)
Software  Testing & it’s  types (DevOps)Software  Testing & it’s  types (DevOps)
Software Testing & it’s types (DevOps)
S Pranav (Deepu)
 
wAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptxwAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptx
SimonedeGijt
 
Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)
VICTOR MAESTRE RAMIREZ
 
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
WSO2
 
Top 5 Task Management Software to Boost Productivity in 2025
Top 5 Task Management Software to Boost Productivity in 2025Top 5 Task Management Software to Boost Productivity in 2025
Top 5 Task Management Software to Boost Productivity in 2025
Orangescrum
 
Best Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small BusinessesBest Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small Businesses
TheTelephony
 
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...
Insurance Tech Services
 
GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?
felipeceotto
 
Leveraging Foundation Models to Infer Intents
Leveraging Foundation Models to Infer IntentsLeveraging Foundation Models to Infer Intents
Leveraging Foundation Models to Infer Intents
Keheliya Gallaba
 
14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework
Angelo Theodorou
 
Key AI Technologies Used by Indian Artificial Intelligence Companies
Key AI Technologies Used by Indian Artificial Intelligence CompaniesKey AI Technologies Used by Indian Artificial Intelligence Companies
Key AI Technologies Used by Indian Artificial Intelligence Companies
Mypcot Infotech
 
Porting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 WebinarPorting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 Webinar
ICS
 
Plooma is a writing platform to plan, write, and shape books your way
Plooma is a writing platform to plan, write, and shape books your wayPlooma is a writing platform to plan, write, and shape books your way
Plooma is a writing platform to plan, write, and shape books your way
Plooma
 
Ad

What are arrays in java script

  • 1. What are Arrays in JavaScript? Before we proceed, you need to understand what arrays really mean. In JavaScript,anarray is a variable that is used to store different data types. It basically stores different elements in one box and canbe later assesssed with the variable. Declaring an array: let myBox = []; // Initial Arraydeclaration in JS Arrays can contain multiple data types let myBox = ['hello', 1, 2, 3, true, 'hi']; Arrays can be manipulated by using several actions known as methods. Some of these methods allow us to add, remove, modify and do lots more to arrays. I would be showing you a few in this article, let’s roll :) NB: I used Arrow functions in this post, If you don’t know what this means, you should read here. Arrow function is an ES6 feature. toString() The JavaScript method toString() converts an array to a string separated by a comma. let colors = ['green', 'yellow', 'blue']; console.log(colors.toString()); // green,yellow,blue join() The JavaScript join() method combines all array elements into a string. It is similar to toString() method, but here you can specify the separator instead of the default comma. let colors = ['green', 'yellow', 'blue']; console.log(colors.join('-')); // green-yellow-blue concat
  • 2. This method combines two arrays together or add more items to an array and then return a new array. let firstNumbers = [1, 2, 3]; let secondNumbers = [4, 5, 6]; let merged = firstNumbers.concat(secondNumbers); console.log(merged); // [1, 2, 3, 4, 5, 6] push() This method adds items to the end of an array and changes the original array. let browsers = ['chrome', 'firefox', 'edge']; browsers.push('safari', 'opera mini'); console.log(browsers); // ["chrome", "firefox", "edge", "safari", "opera mini"] pop() This method removes the last item of an array and returns it. let browsers = ['chrome', 'firefox', 'edge']; browsers.pop(); // "edge" console.log(browsers); // ["chrome", "firefox"] shift() This method removes the first item of an array and returns it. let browsers = ['chrome', 'firefox', 'edge']; browsers.shift(); // "chrome" console.log(browsers); // ["firefox", "edge"] unshift() This method adds an item(s) to the beginning of an array and changes the original array. let browsers = ['chrome', 'firefox', 'edge']; browsers.unshift('safari'); console.log(browsers); // ["safari", "chrome", "firefox", "edge"] You can also add multipleitems at once splice() This method changes an array, by adding, removing and inserting elements. The syntax is: array.splice(index[, deleteCount, element1, ..., elementN])
  • 3.  Index here is the starting point for removing elements in the array  deleteCount is the number of elements to be deleted from that index  element1, …, elementN is the element(s) to be added Removing items after running splice() , it returns the array with the item(s) removed and removes it from the original array. let colors = ['green', 'yellow', 'blue', 'purple']; colors.splice(0, 3); console.log(colors); // ["purple"] // deletes ["green", "yellow", "blue"] NB: The deleteCount does not includethe last index in range. If the second parameter is not declared, every element starting from the given index will be removed from the array: let colors = ['green', 'yellow', 'blue', 'purple']; colors.splice(3); console.log(colors); // ["green", "yellow", "blue"] // deletes ['purple'] In the next example we will remove 3 elements from the array and replace them with more items: let schedule = ['I', 'have', 'a', 'meeting', 'tommorrow']; // removes 4 first elements and replace them with another schedule.splice(0, 4, 'we', 'are', 'going', 'to', 'swim'); console.log(schedule); // ["we", "are", "going", "to", "swim", "tommorrow"] Addingitems To add items, we need to set the deleteCount to zero let schedule = ['I', 'have', 'a', 'meeting', 'with']; // adds 3 new elements to the array schedule.splice(5, 0, 'some', 'clients', 'tommorrow'); console.log(schedule); // ["I", "have", "a", "meeting", "with", "some", "clients", "tommorrow"] slice() This method is similar to splice() but very different. It returns subarrays instead of substrings. This method copies a given part of an array and returns that copied part as a new array. It does not change the original array.
  • 4. The syntax is: array.slice(start, end) Here’s a basic example: let numbers = [1, 2, 3, 4] numbers.slice(0, 3) // returns [1, 2, 3] console.log(numbers) // returns the original array The best way to use slice() is to assign it to a new variable. let message = 'congratulations' const abbrv = message.slice(0, 7) + 's!'; console.log(abbrv) // returns "congrats!" split() This method is used for strings. It divides a string into substrings and returns them as an array. Here’s the syntax:string.split(separator, limit);  The separator here defines how to split a string either by a comma.  The limit determines the number of splits to be carried out let firstName = 'Bolaji'; // return the string as an array firstName.split() // ["Bolaji"] another example: let firstName = 'hello, my name is bolaji, I am a dev.'; firstName.split(',', 2); // ["hello", " my name is bolaji"] NB: If we declare an empty array, like this firstName.split(''); then each item in the string will be divided as substrings: let firstName = 'Bolaji'; firstName.split('') // ["B", "o", "l", "a", "j", "i"] indexOf() This method looks for an item in an array and returns the index where it was found else it returns -1 let fruits = ['apple', 'orange', false, 3] fruits.indexOf('orange'); // returns 1 fruits.indexOf(3); // returns 3 friuts.indexOf(null); // returns -1 (not found)
  • 5. lastIndexOf() This method works the same way indexOf() does except that it works from right to left. It returns the last index where the item was found let fruits = ['apple', 'orange', false, 3, 'apple'] fruits.lastIndexOf('apple'); // returns 4 filter() This method creates a new array if the items of an array pass a certain condition. The syntax is: let results = array.filter(function(item, index, array) { // returns true if the item passes the filter }); Example: Checks users from Nigeria const countryCode = ['+234', '+144', '+233', '+234']; const nigerian = countryCode.filter( code => code === '+234'); console.log(nigerian); // ["+234", "+234"] map() This method creates a new array by manipulating the values in an array. Example: Displays usernames on a page. (Basic friend list display) const userNames = ['tina', 'danny', 'mark', 'bolaji']; const display = userNames.map(item => { return '<li>' + item + '</li>'; }) const render = '<ul>' + display.join('') + '</ul>'; document.write(render);
  • 6. another example: // adds dollar sign to numbers const numbers = [10, 3, 4, 6]; const dollars = numbers.map( number => '$' + number); console.log(dollars); // ['$10', '$3', '$4', '$6']; reduce() This method is good for calculating totals. reduce() is used to calculate a single value based on an array. let value = array.reduce(function(previousValue, item, index, array) { // ... }, initial); example: To loop through an array and sum all numbers in the array up, we can use the for of loop. const numbers = [100, 300, 500, 70]; let sum = 0; for (let n of numbers) { sum += n; } console.log(sum); Here’s how to do same with reduce() const numbers = [100, 300, 500, 70]; const sum = numbers.reduce((accummulator, value) => accummulator + value , 0); console.log(sum); // 970 If you omit the initialvalue, the total will by default start from the first item in the array. const numbers = [100, 300, 500, 70]; const sum = numbers.reduce((accummulator, value) => accummulator + value);
  • 7. console.log(sum); // still returns 970 The snippet below shows how the reduce() method works with all four arguments. More insights into the reduce() method and various ways of using it can be found here and here. forEach() This method is good for iterating through an array. It applies a function on all items in an array const colors = ['green', 'yellow', 'blue']; colors.forEach((item, index) => console.log(index, item)); // returns the index and the every item in the array // 0 "green" // 1 "yellow" // 2 "blue" iteration can be done without passing the index argument const colors = ['green', 'yellow', 'blue']; colors.forEach((item) => console.log(item)); // returns everyitem in the array // "green" // "yellow"
  • 8. // "blue" every() This method checks if all items in an array pass the specified condition and returntrue if passed, else false. check if all numbers are positive const numbers = [1, -1, 2, 3]; let allPositive = numbers.every((value) => { return value >= 0; }) console.log(allPositive); // would return false some() This method checks if an item (one or more) in an array pass the specified condition and return true if passed, else false. checks if at least one number is positive const numbers = [1, -1, 2, 3]; let atLeastOnePositive = numbers.some((value) => { return value >= 0; }) console.log(atLeastOnePositive); // would return true includes() This method checks if an array contains a certain item. It is similar to .some(), but instead of looking for a specific condition to pass, it checks if the array contains a specific item. let users = ['paddy', 'zaddy', 'faddy', 'baddy']; users.includes('baddy'); // returns true If the item is not found, it returns false
  • 9. Summary toString() converts an array to a string separated by a comma. join() combines all array elements into a string. concat combines two arrays together or add more items to an array and then return a new array. push() adds item(s) to the end of an array and changes the original array. pop() removes the last item of an array and returns it shift() removes the first item of an array and returns it unshift() adds an item(s) to the beginning of an array and changes the original array. splice() changes an array, by adding, removing and inserting elements. slice() copies a given part of an array and returns that copied part as a new array. It does not change the original array. split() divides a string into substrings and returns them as an array. indexOf() looks for an item in an array and returns the index where it was found else it returns -1 lastIndexOf() looks for an item from right to left and returns the last index where the item was found. filter() creates a new array if the items of an array pass a certain condition. map() creates a new array by manipulating the values in an array. reduce() calculates a single value based on an array. forEach() iterates through an array, it applies a function on all items in an array every() checks if all items in an array pass the specified condition and return true if passed, else false. some() checks if an item (one or more) in an array pass the specified condition and return true if passed, else false. includes() checks if an array contains a certain item.