简体   繁体   中英

Delete elements of array that end with certain strings in JavaScript

I have an array and I need every element that ends with a certain string to be deleted.

var arr = ["strawberry", "apple", "blueberry"];

I need every element that ends with berry to be deleted. The array should end up like this:

var arr = ["apple"]; 

You can user Array.prototype.filter to create a new, filtered array:

var newArr = arr.filter(function(arrayElement){
    return arrayElement.indexOf("berry") != arrayElement.length - "berry".length;
});

From the docs:

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

So, the provided callback should return true to project the element into the output array, or false to omit it. How you might implement the test is down to you. The test I provide is somewhat naive.

To find items that ends with something we use something$ (the $ indicates the end of string or end of line). If we negate this regex expression we can find items that not ending with that string.
On other hand, arrays in javascript have a filter function that filters the array items based on a filtering function. By combining this two we can create a new array just containing what we want.

 var arr = ["strawberry", "apple", "blueberry"]; var endsWith = "berry" var regx = new RegExp(endsWith+"$"); var result = arr.filter(function(item){return !regx.test(item);}) alert(result);

You can do it using Array.prototype.filter() combined with String.prototype.endsWith() :

// Declaring array of fruits
let arr = ['strawberry', 'apple', 'blueberry'];

// Filtering elements that are not ending with 'berry'
let filtered = arr.filter(fruit => !fruit.endsWith('berry'));

console.log(filtered);
// ['apple']
var fruits = ["strawberry", "apple", "blueberry"];
for(var i=0;i<3;i++){
var a = fruits[i].indexOf("berry") > -1;
    document.getElementById("demo").innerHTML = a;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM