Home > Web Front-end > JS Tutorial > JavaScript array methods.

JavaScript array methods.

Mary-Kate Olsen
Release: 2024-12-08 14:26:11
Original
408 people have browsed it

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!

source:dev.to
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template