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"];
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"];
Share
Improve this question
asked Aug 17, 2015 at 16:12
Dermot O.Dermot O.
411 silver badge2 bronze badges
2
- 1 Please post your attempts so far and we can try to help you out. – Tad Donaghe Commented Aug 17, 2015 at 16:15
- Wele to SO! try solving it yourself, then if you face any problem(s), post your code with details! If you need a start for this problem, look at ways to iterate arrays and array related functions in javaScript. – Sudhansu Choudhary Commented Aug 17, 2015 at 16:19
4 Answers
Reset to default 5You 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 bining 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()
bined 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;
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742398331a4436398.html
评论列表(0条)