Reputation: 1
I would like to filter the items from an array based on a string and save them to a new array to then perform some other functions on that second array. How would I best achieve this?
Here is what I have so far.
for (var i = 0; i < array.length; i++) {
var num = i;
var item = array.entries[i];
var str = item.content;
var newArray = new Array();
if (str.indexOf("filter") !== -1) {
// If the content of the item contains a given string then ad it to the array.
newArray.push(item);
if (num === array.length) {
// When we reach the end of the first array, perform something on the new array.
doSomeFunction();
}
}
function doSomeFunction() {
// Now do something with the new array
for (var j = 0; j < newArray.length; j++) {
// Blah, blah, blah...
}
}
}
Thanks for any help.
Upvotes: 0
Views: 171
Reputation: 2457
Something like this:
function arrayFromArray(a,f){
var b=[];
for (var x=0;x<a.length;x++) {
if (f(a[x])) {
b.push(a[x]);
}
}
return b;
}
function predicateIsEven(i){
return i%2==0;
}
var arr=[1,2,3,4,5,6];
var evens=arrayFromArray(arr,predicateIsEven);
Upvotes: 0
Reputation: 18219
ECMAScript 5 supports the filter
method on arrays.
for example:
> [1,2,3,4].filter(function(v) { return v % 2 == 0})
[ 2, 4 ]
you may refer to MDN's document to see the usage.
But note that this is not supported in some browsers, for compatibility issue, you may consider using es5-shim or underscore.
in your case for doing the work on string arrays. you can use filter
together with map
for example, to filter all strings starting with 'index', then take the trailing number from them.
var ss = [
"index1",
"index2",
"index3",
"foo4",
"bar5",
"index6"
];
var nums = ss.filter(function(s) {
return /^index/.test(s);
}).map(function(s) {
return parseInt(s.match(/(\d+)$/)[1], 10);
});
console.log(nums);
the above script gives you [1,2,3,6]
Upvotes: 2