Add An Item To The Beginning Of An Array In JavaScript Or Node.js
Maybe your like
Arrays are a commonly used data structure in JavaScript. When interacting with arrays, you likely want to manipulate them by adding new items. In some situations, you may want to add items to the beginning of an array.
This tutorial shows you three ways on how to prepend items to an array.
Node.js Series Overview
- Node.js
- Strings
- Streams
- Date & Time
- Arrays
- Promises
- JSON
- Iterators
- Classes
- Numbers
- Objects
- File System
- Map
- Process
- Symbols
- Platform/OS
- HTTPS
- Hashing
- CLI
-
Increase the Memory Limit for Your Process
-
Why You Should Add “node” in Your Travis Config
-
Retrieve a Request’s IP Address in Node.js
-
How to Base64 Encode/Decode a Value in Node.js
-
How to Fix “Uncaught SyntaxError: Cannot use import statement outside a module”
-
Nested Destructuring in JavaScript or Node.js
-
ESM Bypass Cache for Dynamic Imports
-
String Replace All Appearances
-
Generate a Random ID or String in Node.js or JavaScript
-
Remove Numbers From a String in JavaScript or Node.js
-
Get the Part After a Character in a String in JavaScript or Node.js
-
Check If a String Includes All Strings in JavaScript/Node.js/TypeScript
-
Limit and Truncate a String to a Given Length in JavaScript and Node.js
-
How to Generage a UUID in Node.js
-
Split a String into a List of Lines in JavaScript or Node.js
-
Detect if a String is in camelCase Format in Javascript or Node.js
-
Check If a String is in Uppercase in JavaScript or Node.js
-
Get the Part Before First Occurrence in a String in JavaScript or Node.js
-
Get the Part After Last Occurrence in a String in JavaScript or Node.js
-
How to Shuffle the Characters of a String in JavaScript or Node.js
-
Check if a String is Empty in JavaScript or Node.js
-
Left-Trim Characters Off a String in JavaScript or Node.js
-
Lowercase the First Character of a String in JavaScript or Node.js
-
Prepend Characters or Words to a String in JavaScript or Node.js
-
Convert a String to Buffer
-
How to Implement a Custom `toString` Method
-
How to Check if a Value is a ULID
- String Replace All Appearances
- Remove All Whitespace From a String in JavaScript
- Generate a Random ID or String in Node.js or JavaScript
- Remove Extra Spaces From a String in JavaScript or Node.js
- Remove Numbers From a String in JavaScript or Node.js
- Get the Part Before a Character in a String in JavaScript or Node.js
- Get the Part After a Character in a String in JavaScript or Node.js
- How to Check if a Value is a String in JavaScript or Node.js
- Check If a String Includes All Strings in JavaScript/Node.js/TypeScript
- Check if a Value is a String in JavaScript and Node.js
- Limit and Truncate a String to a Given Length in JavaScript and Node.js
- Split a String into a List of Characters in JavaScript and Node.js
- How to Generage a UUID in Node.js
- Reverse a String in JavaScript or Node.js
- Split a String into a List of Lines in JavaScript or Node.js
- Split a String into a List of Words in JavaScript or Node.js
- Detect if a String is in camelCase Format in Javascript or Node.js
- Check If a String Is in Lowercase in JavaScript or Node.js
- Check If a String is in Uppercase in JavaScript or Node.js
- Get the Part After First Occurrence in a String in JavaScript or Node.js
- Get the Part Before First Occurrence in a String in JavaScript or Node.js
- Get the Part Before Last Occurrence in a String in JavaScript or Node.js
- Get the Part After Last Occurrence in a String in JavaScript or Node.js
- How to Count Words in a File
- How to Shuffle the Characters of a String in JavaScript or Node.js
- Append Characters or Words to a String in JavaScript or Node.js
- Check if a String is Empty in JavaScript or Node.js
- Ensure a String Ends with a Given Character in JavaScript or Node.js
- Left-Trim Characters Off a String in JavaScript or Node.js
- Right-Trim Characters Off a String in JavaScript or Node.js
- Lowercase the First Character of a String in JavaScript or Node.js
- Uppercase the First Character of a String in JavaScript or Node.js
- Prepend Characters or Words to a String in JavaScript or Node.js
- Check if a String is a Number
- Convert a String to Buffer
- Prevent Line Breaks in String Template Literals
- How to Implement a Custom `toString` Method
- What Is `Symbol.toStringTag` and How to Use It
- How to Check if a Value is a ULID
-
Get Number of Seconds Since Epoch in JavaScript
-
Increase a Date in JavaScript by One Week
-
Add Month(s) to a Date in JavaScript or Node.js
-
Get the Current Year in JavaScript or Node.js
-
How to Convert a UNIX Timestamp to a Date in JavaScript or Node.js
-
Get Yesterday's Date in JavaScript or Node.js
-
Add Hours to a Date in JavaScript or Node.js
-
Check If a Date is Tomorrow in JavaScript or Node.js
-
How to Format a Date YYYY-MM-DD in JavaScript or Node.js
-
Get Number of Days in a Month
-
How to Reset and Empty an Array
-
Clone/Copy an Array in JavaScript and Node.js
-
Sort an Array of Integers in JavaScript and Node.js
-
Check If an Array Contains a Given Value in JavaScript or Node.js
-
Append an Item at the End of an Array in JavaScript or Node.js
-
Split an Array Into Smaller Array Chunks in JavaScript and Node.js
-
How to Exit, Stop, or Break an Array#forEach Loop in JavaScript or Node.js
-
How to Reverse an Array in JavaScript and Node.js
-
Sort an Array of Objects in JavaScript, TypeScript or Node.js
-
Join an Array of Strings to a Single String Value
-
Run Async Functions/Promises in Sequence
-
Run Async Functions in Batches
-
Detect if Value Is a Promise in Node.js and JavaScript
-
Thenables and Creating Your Own Promises
- Callback and Promise Support in your Node.js Modules
- Run Async Functions/Promises in Sequence
- Run Async Functions/Promises in Parallel
- Run Async Functions in Batches
- How to Fix “Promise resolver undefined is not a function” in Node.js or JavaScript
- Detect if Value Is a Promise in Node.js and JavaScript
- Overview of Promise-Based APIs in Node.js
- Thenables and Creating Your Own Promises
-
Write a JSON Object to a File
-
Securely Parse JSON
-
Check If a Value Is Iterable in JavaScript or Node.js
-
What is `Symbol.iterator`?
-
Retrieve the Class Name at Runtime in JavaScript and Node.js
-
Deprecate a Method in JavaScript and TypeScript
- Extend Multiple Classes (Multi Inheritance)
- Retrieve the Class Name at Runtime in JavaScript and Node.js
- Deprecate a Method in JavaScript and TypeScript
-
Ensure a Positive Number in JavaScript or Node.js
-
Check If a Number has Decimal Places in JavaScript or Node.js
-
Convert Boolean to Number
-
Check if a Value is a Number
- Generate a Random Number in Range With JavaScript/Node.js
- Ensure a Positive Number in JavaScript or Node.js
- Check if a Number Is Infinity
- Check If a Number has Decimal Places in JavaScript or Node.js
- Use Numeric Separators for Better Readability
- Convert Boolean to Number
- Convert Number to Boolean
- Check if a Value is a Number
-
How to Check if an Object is Empty in JavaScript or Node.js
-
How to Snake_Case Keys of an Object in JavaScript or Node.js
-
How to Get All Keys (Including Symbols) from an Object in JavaScript or Node.js
-
Iterate Through an Object’s Keys and Values in JavaScript or Node.js
-
Check If a Value Is an Object in JavaScript or Node.js
-
How to Lowercase Keys of an Object in JavaScript or Node.js
-
Get a File’s Created Date
-
How to Create an Empty File
-
How to Rename a File
-
Check If a Path Is a File
-
How to Touch a File
-
Check If a Directory Is Empty
-
Get a File‘s Extension
-
Get a File Name (With or Without Extension)
-
Delete a File From Disk
-
Check if a Path is a Socket
-
Check if a Path is a File URL
-
What is `Fs.realpath`?
- Get a File’s Created Date
- Get a File’s Last Modified or Updated Date of a File
- How to Create an Empty File
- Check If a Path or File Exists
- How to Rename a File
- Check If a Path Is a Directory
- Check If a Path Is a File
- Retrieve the Path to the User’s Home Directory
- How to Touch a File
- Read File Content as String
- Check If a Directory Is Empty
- How to Create a Directory (and Parents If Needed)
- Get a File‘s Extension
- Get the Size of a File
- Get a File Name (With or Without Extension)
- Read a JSON File
- Delete a File From Disk
- Check if a Path is a SymLink (Symbolic Link)
- Check if a Path is a Socket
- Check if a Path is a FIFO File (Named Pipe)
- Check if a Path is a File URL
- Handling `fs.Stats` Constructor is Deprecated
- What is `Fs.realpath`?
-
Transform to an Object
- Create From Object
- Transform to an Object
-
Show Your NODE_MODULE_VERSION
- Determine the Node.js Version Running Your Script
- Show Your NODE_MODULE_VERSION
-
Detect if Running on Linux
-
Detect if Running on Windows
-
Constant for Platform-Specific Newline
-
Retrieve the OS Directory for Temporary Files
- Detect if Running on Linux
- Detect if Running on macOS
- Detect if Running on Windows
- Check if Running on 64bit or 32bit Platform
- Constant for Platform-Specific Newline
- Determine the Current Operating System
- Retrieve the OS Directory for Temporary Files
-
Strict Type for Request Headers with TypeScript
- How to Download a File
- Strict Type for Request Headers with TypeScript
-
Retrieve the List of Supported Hash Algorithms
-
Calculate a SHA512 Hash
- Calculate an MD5 Hash
- Retrieve the List of Supported Hash Algorithms
- Calculate a SHA256 Hash
- Calculate a SHA512 Hash
-
Using the Styletext Utility for Terminal Text Formatting
- Using the Styletext Utility for Terminal Text Formatting
3 Ways Adding Items to the Beginning of a JavaScript Array
JavaScript supports different ways of adding items to the beginning of an array. You can use the native Array#unshift method, create a new array in combination with spreading existing items into the new array or create a new array by concatenating two arrays.
Prepend Items to an Existing Array
The Array#unshift method adds one or more items to the beginning of an array.
Notice: Array#unshift returns the new length of the array, not the array containing the new item(s):
const ids = [1, 2] const newArrayLength = ids.unshift(3) // 3 // the value of "ids" is [3, 1, 2] ids.unshift(4) // the value of "ids" is [4, 3, 1, 2] // or prepend multiple values ids.unshift(5, 6, 7) // the value of "ids" is [5, 6, 7, 4, 3, 1, 2]Add and Spread Items Into a New Array
You can also create a new array and add the new items at the beginning. This is a short and concise way in combination with the spread operator to add the values of an existing array:
const ids = [1, 2, 3] const newIds = [4, ...ids] // [4, 1, 2, 3] const newIds = [4, 5, 6, ...ids] // [4, 5, 6, 1, 2, 3]Concat(enate) Arrays Items
You may also create a new array of the items you want to prepend to the existing array. Then, concatenate the existing items to the end of the new array. This keeps the new items in the front and appends the existing ones to the end:
const ids = [1, 2, 3] const newIds = [4, 5, 6].concat(ids) // the value of "newIds" is [4, 5, 6, 1, 2, 3]All three ways allow you to prepend one or more items to the beginning of an array. Enjoy!
What Should You Use?
Well, use what you like best!
I prefer Array#concat when building an array pipeline by chaining further operations, like Array#map, Array#filter, or Array#find.
In situations where I only want to prepend the item without additional operations, I’m using the spread operator.
In terms of performance: I don’t really care about performance optimizations on my side. I’m relying on the JavaScript runtime to optimize the code for me. This gives me the freedom of writing the code I like to read 😃
Tag » Add Element Array Js
-
How To Append Something To An Array? - Stack Overflow
-
JavaScript Array Push() Method - W3Schools
-
How To Add To An Array With The Push, Unshift, And Concat Functions
-
totype.push() - JavaScript - MDN Web Docs
-
5 Way To Append Item To Array In JavaScript
-
How To Add Elements Into An Array In JavaScript - Linux Hint
-
How To Add New Elements At The Beginning Of An Array In JavaScript
-
JavaScript: How To Insert Elements Into A Specific Index Of An Array
-
Javascript Array Push: How To Add Element In Array - AppDividend
-
JavaScript Program To Add Element To Start Of An Array - Programiz
-
JavaScript Program To Insert Item In An Array - Programiz
-
Add An Element To An Array In JavaScript - Mastering JS
-
TypeScript - Array Push() - Tutorialspoint
-
Add Element To Array At Specific Index In JavaScript | Bobbyhadz
-
How To Insert An Element In A Specific Index In JavaScript Array
-
JavaScript Array Splice(): Delete, Insert, And Replace
-
How To Add Item To An Array At A Specific Index In JavaScript
-
Javascript Tutorial | Adding Elements To Array In JavaScript - Morioh
-
How To Add Element To UseState Array In JavaScript - Simplernerd