Home  >  Article  >  Web Front-end  >  nodejs array deletion specified

nodejs array deletion specified

王林
王林Original
2023-05-27 22:17:06835browse

When developing with Node.js, operating arrays is a very common thing. In some cases, we need to delete specified elements from the array. This can be achieved through the following methods.

1. Use the splice() method

The splice() method can delete any element in the array. This method accepts two parameters. The first parameter is the start of the element to be deleted. position, the second parameter is the number of elements to remove.

For example:

let arr = ['apple', 'banana', 'orange', 'grape'];
let index = arr.indexOf('orange'); //获取orange的下标
arr.splice(index, 1); //删除元素
console.log(arr); //输出:["apple", "banana", "grape"]

The indexOf() method is used here to get the subscript of the element in the array. Then use the splice() method to specify the starting position and number of elements to be deleted.

2. Use the filter() method

Another method is to use the filter() method. This method can traverse the entire array and filter out elements that meet the conditions based on specific conditions. Finally, Return a new array.

For example:

let arr = ['apple', 'banana', 'orange', 'grape'];
let newArr = arr.filter(item => item !== 'orange');
console.log(newArr); //输出:["apple", "banana", "grape"]

The filter() method is used here, passing in an arrow function as a parameter, filtering out elements that are not equal to 'orange', and finally returning a new array.

3. Use the splice() method in combination with the indexOf() method

In actual development, we may need to delete all elements in the array that meet a certain condition. At this time, it can be implemented by combining the splice() method and the indexOf() method.

For example:

let arr = ['apple', 'banana', 'orange', 'grape', 'orange'];
let index = arr.indexOf('orange');
while(index !== -1){
  arr.splice(index, 1);
  index = arr.indexOf('orange');
}
console.log(arr); //输出:["apple", "banana", "grape"]

Here, use the indexOf() method to get the subscript of the first 'orange', and then use a while loop to delete an 'orange' every time it is found. Until there is no more 'orange' in the array.

Summary

The above are several ways to delete specified elements in an array in Node.js. Which method should be chosen depends on the specific scenario. In the actual development process, selection needs to be made based on actual conditions.

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

Statement:
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