Home Web Front-end JS Tutorial JavaScript array methods.

JavaScript array methods.

Dec 08, 2024 pm 02:26 PM

Let's go to work without saying much. In this post, we will get acquainted with the methods of arrays in the javascript programming language and work on related issues.


Add element, change.

  • length()
  • push()
  • concat()

Turn off.

  • pop()
  • shift()
  • splice()
  • delete array[i]

search

  • find(function())
  • indexOf()

Arrange

  • sort() for numbers and for strings

Reverse

  • reverse()

Add and modify items.

The

length method finds the number of elements, or the length, of the array.
It should be noted that the type of arrays in Javascript is object. If you have learned languages ​​like c/c or java before, this may seem a bit confusing. In JavaScript, arrays themselves are actually data-type , which is different from arrays in c/c. In JS, you can store different types of data in one array.

// Arrayning uzunligi, o'lchami
const array = ["nimadir", "kimdir", true, 55, 4.6];
console.log(`arrayning uzunligi ${array.length}`);
Copy after login
Copy after login
Copy after login

JavaScript array metodlari.


Add a new element from the end of an array.

You may have a question. Is it possible to change the value of a constant variable? Yes, we are inserting a new element through the push() method, but we are not setting a new value to the array.

// push(), array oxiriga yangi element qo'shish
const array = ["nimadir", "kimdir", true, 55, 4.6];
array.push("yangi element");
console.log(`arrayning uzunligi: ${array} \n`);
Copy after login
Copy after login
Copy after login

JavaScript array metodlari.


Combine two arrays (concatenate).

concat() method will combine two arrays.

// concat(), ikki arrayni birlashtirish
let array1 = ["nimadir", "kimdir", true, 55, 4.6];
let array2 = [8, 3, 9];
console.log("array1: " + array1, "\n", "array2: " + array2 + "\n");

let result = array1.concat(array2);
console.log(
  `Ikki array bitta yangi arrayga birlashtirildi: result [${result}] \n`
);
Copy after login
Copy after login
Copy after login

JavaScript array metodlari.


Deleting an element from an array.

There are several different ways to delete array elements in JavaScript.
pop() method is used to remove one element from the end of the array.

// pop(), arrayning oxiridan bitta element o'chiradi
let array1 = [6, "satr", true, 55, 4.6];
console.log(`\navval:  [${array1}]\n`);

array1.pop();
console.log(`keyin:  [${array1}]\n`);
Copy after login
Copy after login

JavaScript array metodlari.


The

shift() method removes one element from the beginning of the array

// shift() Metodi

const array = [44, 5.3, 2, 14, 98, "text", "olma"];
console.log(`\navval: [${array}] \n`);

array.shift();
console.log(`keyin: 44 arrayda emas [${array}]\n`);
Copy after login
Copy after login

JavaScript array metodlari.


The

splice() method is unique in that it is not only used to delete elements, but also to modify data. For deletion purposes, the method takes two values.

  • first: is the starting index for deleting elements.
  • second: how many elements to delete.

For example: const array = [44, 5.3, 2, 14, 98, "text", "apple"]; there is. We want to delete 2 elements, starting from index 3, i.e. 14 (14 itself is deleted), 2 elements.

// Arrayning uzunligi, o'lchami
const array = ["nimadir", "kimdir", true, 55, 4.6];
console.log(`arrayning uzunligi ${array.length}`);
Copy after login
Copy after login
Copy after login

JavaScript array metodlari.
For the purpose of replacement, splice() is used as follows.

  1. start index array.splice(3, ...)
  2. how many elements to swap array.splice(3, 2, ...)
  3. new elements to be inserted accordingly array.splice(3, 2, "new1", "new2")
// push(), array oxiriga yangi element qo'shish
const array = ["nimadir", "kimdir", true, 55, 4.6];
array.push("yangi element");
console.log(`arrayning uzunligi: ${array} \n`);
Copy after login
Copy after login
Copy after login

JavaScript array metodlari.


The

delete array[i] method is the easiest way to delete an array element. In this case, the index of the element to be deleted is written instead of [i].

// concat(), ikki arrayni birlashtirish
let array1 = ["nimadir", "kimdir", true, 55, 4.6];
let array2 = [8, 3, 9];
console.log("array1: " + array1, "\n", "array2: " + array2 + "\n");

let result = array1.concat(array2);
console.log(
  `Ikki array bitta yangi arrayga birlashtirildi: result [${result}] \n`
);
Copy after login
Copy after login
Copy after login

JavaScript array metodlari.


Searching from an array

The

find(function()) method is used to search for a given element from an array. A function is written to this method as a value, and the function is given the element to search for. The function does not return an index, if the searched element is present in the array, it returns this element, otherwise it returns undefined.

// pop(), arrayning oxiridan bitta element o'chiradi
let array1 = [6, "satr", true, 55, 4.6];
console.log(`\navval:  [${array1}]\n`);

array1.pop();
console.log(`keyin:  [${array1}]\n`);
Copy after login
Copy after login

JavaScript array metodlari.


indexOf() method returns the index of the searched element.

// shift() Metodi

const array = [44, 5.3, 2, 14, 98, "text", "olma"];
console.log(`\navval: [${array}] \n`);

array.shift();
console.log(`keyin: 44 arrayda emas [${array}]\n`);
Copy after login
Copy after login

JavaScript array metodlari.


Arrange

sort() method, this is where JavaScript's "headache" begins. At first glance, the sort() method looks simple, but there is actually another process going on behind the scenes. By default, sort() sorts strings , but can sort correctly if an integer or numeric value is given. But JavaScript sorts numbers if it wants to, not if it doesn't (just kidding):)

// splice() Metodi

const array = [44, 5.3, 2, 14, 98, "text", "olma"];
console.log(`\navval: [${array}] \n`);

array.splice(3, 2);

console.log(`keyin: 14 va 98 elementlari o'chdi [${array}]\n`);
Copy after login

JavaScript array metodlari.


in numerical values as follows.

// splice() Metodi

const array = [44, 5.3, 2, 14, 98, "text", "olma"];
console.log(`\navval: [${array}] \n`);

array.splice(3, 2, "yangi1", "yangi2");

console.log(`keyin: 14 va 98 elementlari almashtirildi [${array}]\n`);
Copy after login

JavaScript array metodlari.


So what's the problem?

You can say, let's continue.

// Arrayning uzunligi, o'lchami
const array = ["nimadir", "kimdir", true, 55, 4.6];
console.log(`arrayning uzunligi ${array.length}`);
Copy after login
Copy after login
Copy after login

JavaScript array metodlari.

Stop, look at the result, sorted array: [100,1021,30,45,61,8] what's that!?
JavaScript sorts an array as a string. Even if a number is given, it will be transferred to ascii code and sorted lexicographically, i.e. like a string. This will cause an error. In the problem, 100 should be the last number, and 30 should be before 100. as a char, 1 precedes 3, so an error occurs (see ascii table!). To fix this, we give function() to the sort() method.

// push(), array oxiriga yangi element qo'shish
const array = ["nimadir", "kimdir", true, 55, 4.6];
array.push("yangi element");
console.log(`arrayning uzunligi: ${array} \n`);
Copy after login
Copy after login
Copy after login
The function

array.sort((a, b) => a - b); compares two elements in an array and determines their order.

  • a and b: These are the two elements from the array that are compared. The sort() method compares all elements pairwise (for example, a and b) and arranges them according to the result of the comparison function.
  • a - b: By calculating these differences, the order of the elements is determined:
  1. If a - b is negative (ie, a < b), a precedes b.
  2. If a - b is positive (ie, a > b), b precedes a.
  3. If a - b is zero (ie, a === b), then they are not mutually exclusive.

Result:

JavaScript array metodlari.


Flipping

The

reverse() method creates an array that is the reverse of the array given by its name.

// concat(), ikki arrayni birlashtirish
let array1 = ["nimadir", "kimdir", true, 55, 4.6];
let array2 = [8, 3, 9];
console.log("array1: " + array1, "\n", "array2: " + array2 + "\n");

let result = array1.concat(array2);
console.log(
  `Ikki array bitta yangi arrayga birlashtirildi: result [${result}] \n`
);
Copy after login
Copy after login
Copy after login

Result:

JavaScript array metodlari.


I hope you have gained knowledge about JavaScript array methods through this post, share this post with your loved ones who are learning JS!

Questions to review:

1. Add element, change:

a. length()

Problem: Imagine a large array containing 1000 values. If you only need to output the number of elements in an array, what method would you use? How does the number of elements change with any changes to the array?
Problem: If you need to add 1000 new elements to the end of a given array, determine the length of the array. Which method is the most effective to use for this?

b. push()

Problem: You have an array where every element is the same. Every time you add a new element, you must replace the element at the end of the array. How do you optimize these operations?
Problem: You have an array called tasks that contains various tasks that need to be performed. Each time you need to add a new task and update the task at the end of the list. How do you do this?

c. concat()

Problem: You need to merge two arrays and display them in the same format. The first array contains only simple numbers, and the second contains only numeric strings. How to create a new array from them and output all the numbers in numeric format?
Problem: You have two arrays, one containing information about users and the other containing the login history of users. You need to merge these arrays, but you only want to display the active state histories of the users. How do you do this?

2. Delete:

a. pop()

Problem: You have multiple user lists, and each time you need to remove the last user from the list. But you only want to keep active users from the last 3 days. How can you manage them?
Problem: You have an array named books that contains information about various books. Each time you need to delete the last book and add a new book. How do you do it?

b. shift()

Problem: Imagine a queue process where users are waiting for their turn. Each time you log out of the next user and enter a new user. How do you do this process?
Problem: You have an array organized by user login time. You must unsubscribe the very first user each time. How do you do this?

c. splice()

Problem: You have a list of students and each time you need to change or remove 3 students from the list. How do you do this process?
Problem: You have a list of issues. Each time several issues need to be removed and changed. When changing an issue, the other issues must remain in the correct order. How do you do this?

d. delete array[i]

Problem: You have a large array, and you need to delete an element based on its index. What should be done when deleting an element, taking into account how other elements in the array are changed?
Problem: You have a list of customers and each customer has a unique ID number. What method can be used to unregister a customer for a given ID?

3. Search:

a. find(function())

Problem: You have a list of users. Each user has an ID number and a name. You only need to get the information of the user whose name is "John". How do you do this?
Problem: You have a list of products, and each product has a name and a price. You only need to look for products with a price above 100. How do you do this?

b. indexOf()

Problem: You have a list of books, and each book has a title and an author. If the user searches for a book, determine which index it is in by name.
Problem: You have a list of products and each product is assigned a unique identification number. If a user is looking for a product, you should be able to find it based on its ID number. How is this done?

4. Order:

a. sort()(for numbers)

Problem: You have multiple student ratings. Sort grades from lowest to highest, but sort students with the same grade by name.
Problem: You have an array containing the prices of products. You can sort the prices in descending order, but if the prices are the same, sort them by sale date.

b. sort()(for strings)

Problem: You have an array of customer names. You should sort them alphabetically, but only by uppercase
Problem: You have the titles of the books. You want to sort all the books by the length of the words in them. How do you do this?

5. Click:

a. reverse()

Problem: You have an array of multiple numbers. You must output this array in reverse order. How to calculate the changes of this?
Problem: You have a list of texts and you want to output the texts in reverse order. What would you get if the texts were all the same length?

bugs and questions

The above is the detailed content of JavaScript array methods.. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1240
24
Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

See all articles