0

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.

1
  • num will never reach array.length, so it's not a good way to check if you're at the end of the array - also, don't declare a function in your loop Commented Jan 29, 2012 at 3:19

2 Answers 2

2

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]

Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.