JavaScript Basic Array Functions
K-Sato

K-Sato @k_penguin_sato

About: Software Engineer

Joined:
Nov 14, 2018

JavaScript Basic Array Functions

Publish Date: Nov 11 '19
43 72

Introduction

Here are some of the most fundamental JS array functions.

Assume the code below is declared at the top level in the following examples.

var arr = [1, 2, 3, 4, 5];
Enter fullscreen mode Exit fullscreen mode

Add or Remove items

pop()/push()

pop(): Removes the last element of an array, and returns that element.
push(): Adds new elements to the end of an array, and returns the new length.

arr.push(6);
console.log(arr); //=> [1, 2, 3, 4, 5, 6]

arr.pop(6);
console.log(arr); //=>  [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

shift()/unshift()

shift(): Removes the first element of an array, and returns that element.
unshift(): Adds new elements to the beginning of an array, and returns the new length.

arr.unshift(0);
console.log(arr); //=> [0, 1, 2, 3, 4, 5]

arr.shift();
console.log(arr); //=>  [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

slice()

Selects a part of an array, and returns the new array.

let a4 = arr.slice(0, 3);
console.log(a4); //=>  [1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

splice()

Adds/Removes elements from an array.

var months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// inserts at 1st index position
console.log(months);
// expected output: Array ['Jan', 'Feb', 'March', 'April', 'June']

months.splice(4, 1, 'May');
// replaces 1 element at 4th index
console.log(months);
// expected output: Array ['Jan', 'Feb', 'March', 'April', 'May']
Enter fullscreen mode Exit fullscreen mode

concat()

Joins two or more arrays, and returns a copy of the joined arrays.

let a1 = arr.concat([6, 7]);
console.log(a1); //=> [1, 2, 3, 4, 5, 6, 7]
Enter fullscreen mode Exit fullscreen mode

Iterate items

forEach()

Calls a function for each array element.

function repeat(ele) {
  console.log(ele);
}
arr.forEach(repeat); //=> 1 2 3 4 5
Enter fullscreen mode Exit fullscreen mode

Search in array

indexOf()

Looks for item starting from index from, and returns the index where it was found, otherwise -1.

console.log(arr.indexOf(0)) //=> 1
console.log(arr.indexOf(10)) //=> -1
Enter fullscreen mode Exit fullscreen mode

find()/findIndex()

Returns the value of the first element in an array that pass a test.

console.log(arr.find(num => num > 2)); //=> 3
console.log(arr.findIndex(num => num > 2)); //=> 2
Enter fullscreen mode Exit fullscreen mode

includes()

Check if an array contains the specified element.

console.log(arr.includes(2)); //=> true
Enter fullscreen mode Exit fullscreen mode

filter()

Creates a new array with every element in an array that pass a test.

let a2 = arr.filter(num => num > 3);
console.log(a2); //=> [4, 5]
Enter fullscreen mode Exit fullscreen mode

Transform array

map()

Creates a new array with the result of calling a function for each array element.

a3 = arr.map(ele => ele - 1);
console.log(a3); //=> [0, 1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

sort()

Sorts the elements of an array.

let array = [4, 2, 3, 4, 5, 6, 7];
console.log(array.sort()); //=> [2, 3, 4, 4, 5, 6, 7]
Enter fullscreen mode Exit fullscreen mode

reverse()

The method arr.reverse reverses the order of elements in arr.

console.log(arr.reverse()) //=> [5, 4, 3, 2, 1];
Enter fullscreen mode Exit fullscreen mode

reduce()

The reduce() method reduces the array to a single value.

The reduce() method executes a provided function for each value of the array (from left-to-right).

Here is the basic syntax.

let value = arr.reduce(function(previousValue, item, index, array) {
  // ...
}, initial);
Enter fullscreen mode Exit fullscreen mode
  • item – is the current array item.
  • index – is its position.
  • array – is the array.
  • previousValue – is the result of the previous function call, initial for the first call.
let result = arr.reduce((sum, current) => sum + current, 0);

console.log(result); //=> 15
Enter fullscreen mode Exit fullscreen mode

references

Comments 72 total

  • Surijulia
    SurijuliaJun 6, 2022

    Thanks for your post, it's very helpful I hope in the future you will provide more information. I will visit and support the article for you
    Click on drift hunters to play the hot game

    • haadi muhammed
      haadi muhammedMar 21, 2024

      As businesses undergo continuous evolution, the demand for advanced tools becomes increasingly apparent. Delve into the transformative journey of Inventory Management Software, witnessing its progression from conventional approaches to cutting-edge digital solutions. Explore how these systems, including Ebrsoftware's Inventory Software transcend traditional manual processes, ushering in a new era of unparalleled efficiency for businesses navigating the complexities of modern operations.

  • markhalland
    markhallandJun 10, 2022

    thankyou for your amazing content and likes it ,well if any one looking for the good services for take my course then click here for it.

  • Real USAJacket
    Real USAJacketAug 27, 2022

    I am looking for some good blog sites for studying. I was searching over search engines and found your blog site. Well i like your high quality blog site design plus your posting abilities. Keep doing it. Washington Commanders Jacket

  • Anahata Organic
    Anahata OrganicNov 23, 2022

    Hey i just got this site from google and wl use for blog post. I m going to post relate dhoop sticks

  • totogorae
    totogoraeMay 1, 2023

    I really admire your writing! 토토사이트

  • totogorae
    totogoraeMay 1, 2023

    I needed to thank you for this wonderful read!! I absolutely loved every little bit of it. 먹튀검증

  • totogorae
    totogoraeMay 1, 2023

    I have to thank you for the efforts you’ve put in writing this blog. I’m hoping to check out the same high-grade blog posts by you later on as well. 토토사이트

  • totogorae
    totogoraeMay 1, 2023

    Can you tell us more about this? I’d want to find out some additional information. 토토사이트

  • totogorae
    totogoraeMay 1, 2023

    This is my first time I visit here. I found so many engaging stuff in your blog, particularly its conversation. 토토사이트

  • totogorae
    totogoraeMay 1, 2023

    I have to thank you for the efforts you’ve put in writing this blog. I’m hoping to check out the same high-grade blog posts by you later on as well. 토토사이트

  • Lerenjack
    LerenjackMay 30, 2023

    This is definitely useful information if you want to keep your contacts update and organized. Thank you! Squid Game 2021 Green Jacket

  • Akala Emmanuel
    Akala EmmanuelJul 19, 2023

    Your article contains information that is not available anyplace else. It is my sincere wish that you persist to write such wonderful posts Luke Cage Mike Colter Jacket

  • Carl Eliezer
    Carl EliezerMay 29, 2024

    I wanted to take a moment to let you know how much I appreciate the amazing stuff you have been sharing. Your writings are consistently very perceptive and jam-packed with useful knowledge. I am a small business owner, and I have found your techniques and recommendations to be of great assistance in navigating the tricky world of SEO. Your commitment to offering insightful counsel is clear, and it's having a significant impact on how I manage my internet presence. Checking out the best SEO Services for small business you offer is highly recommended for anyone trying to improve their SEO efforts. Maintain the great work; your knowledge and enthusiasm are evident in each and every post!

  • Fisher Lam
    Fisher LamMay 30, 2024

    This place has been incredibly helpful and has taught me so much! I'm genuinely excited to delve deeper into these ideas and see where they take me. Thank you for sharing your knowledge.
    Purple Moto Leather Jacket

  • Louis Barry
    Louis BarryJun 11, 2024

    Your writing is brilliant in so many ways. It's instructive as well as hospitable. I have so many more ideas now that I've read your blog. I sincerely appreciate it. Lana Del Rey Ferrari Jacket

  • Black Leather Jackets
    Black Leather JacketsJun 21, 2024

    Great intro to JavaScript array basics! Concise and clear explanations helped me understand quickly. Plus, check out black leather jackets for stylish attire to complement your coding skills!

  • Carl
    CarlJun 24, 2024

    Just pure classic stuff from you here. I have never seen such a brilliantly written article in a long time. I am thankful to you that you produced this! Also, please take time to check out some Security Guard Services in Riverside.

  • tiffany jorge
    tiffany jorgeJun 25, 2024

    If you wish to maintain your contacts current and structured, this knowledge is undoubtedly helpful. I'm grateful. Movies 2024 Outfits

  • Carl
    CarlJul 1, 2024

    Absolutely delighted with the insightful content shared by the HTN Corporation on their website! The articles are not only informative but also genuinely uplifting. It's evident that the authors put a lot of effort into crafting such valuable resources. Keep up the great work! For more enriching reads, visit HTN Corporation.

  • Black Jacket
    Black JacketJul 23, 2024

    Great overview of basic JavaScript array functions! Your examples clearly demonstrate how to manipulate arrays with methods like pop(), push(), shift(), and unshift(). For anyone looking to dive deeper into programming or fashion, don’t miss checking out my website for the latest trends in Black leather Jacket

    • BEST NEW SONGS
      BEST NEW SONGSSep 19, 2024

      boss matka Very nice article, I just stumbled upon your blog, it’s a great site, thanks for sharing it with everyone. I will bookmark this site and check back regularly for posts.

  • nytwordlehints
    nytwordlehintsAug 1, 2024

    Optimize your Java apps using Java Decompiler Online. Analyze, decompile, java decompiler online and improve code to enhance performance and gain insights for a better user experience and streamlined development.

  • React Hunt
    React HuntAug 9, 2024

    I'm so excited to share this! With my recent engagement, I wanted to treat myself, and what better way than to book some time at SEVlaser? A friend introduced me to their amazing services, and I'm thrilled with the results. Reading all the positive reviews here, I had to join in and share my happiness. If you're considering laser treatments, check out Laser Hair Removal in Chicago. It's truly worth it!

  • Carl Eliezer
    Carl EliezerAug 28, 2024

    Naturally an outstanding attempt! Seeing such well-reasoned and articulate ideas written out is inspiring. In addition to being nice, the writing was excellent. Please visit Laser Hair Removal in San Diego for more information and skilled assistance.

  • Lerenjack
    LerenjackAug 29, 2024

    Lerenjack gets your hands on the most exclusive piece by Jackets, and Leather Jackets Apparel with an amazing discount. Mogul Moves Mint Hoodie

  • Jonafe
    JonafeSep 11, 2024

    I’m so thrilled to share my excitement here! After reading the wonderful comments about Laser Hair Removal, I wanted to add my own. Having recently celebrated a significant milestone, I was introduced to SEVlaser and it truly made a difference. The positive experiences shared by others convinced me to give it a go, and I couldn’t be happier with the results. It’s a fantastic gift to yourself, and the glowing reviews just make it even more appealing. Check out more at Laser Hair Removal.

  • BEST NEW SONGS
    BEST NEW SONGSSep 19, 2024

    Thanks for sharing such an amazing post keep it up satta matka

  • Faux Fur Leather Jacket
    Faux Fur Leather JacketOct 16, 2024

    Thank you for sharing this information! I really appreciate the insights and the clarity you can check also Faux Fur Leather Jacket

  • Celeb Leather Jackets
    Celeb Leather JacketsJan 18, 2025

    "JavaScript arrays are so versatile! From .map() to .filter(), mastering them feels as rewarding as finding the perfect costume fit!"

  • Babak Painex
    Babak PainexJan 30, 2025

    This article is a great resource for anyone considering solar-powered surveillance options. The guide on Solar Mobile Surveillance Trailers in Indio explains the benefits of these mobile units and how they offer flexible, eco-friendly security solutions. If you're looking to enhance your security while keeping things green, this is a must-read!

  • Amelie Zilber
    Amelie ZilberMar 6, 2025

    This is the first time that I visit here. I found so many exciting matters in this particular blog, One thing I would like to request you that pls keep posting such type of informative blog. good winter jackets

  • Luna Eleanor
    Luna EleanorApr 21, 2025

    Great post! This information is incredibly helpful. Thank you for sharing these useful tips! Web Series Costumes

  • Reff PBN
    Reff PBNMay 19, 2025
Add comment