2

Have a function that returns an array of objects. The array has a rate object that has a name field. Inside the name field are names such as "Slow speed" and "Fast speed".

I have written the following in hopes to create a new array that will filter out the array values and just return only those with "Slow" that matches from the rates[i].name.

So far I am encountering this error in my dev console. "Uncaught TypeError: value.substring is not a function"

var rates = myArray();
var index, value, result;
var newArr = [];

for (index = 0; index < rates.length; ++index) {
    //value = rates[index];
    if (value.substring(0, 5) === "Stand") {
        result = value;
        newArr.push();
        break;
    }
}

Part of array return in console.

"rates":[{"id":1123,"price":"1.99","name":"Slow speed - Red Car","policy":{"durqty":1,"durtype":"D","spdup":15000,"spddwn":15000}
4castle
  • 32,613
  • 11
  • 69
  • 106
VanCoon
  • 422
  • 4
  • 20

2 Answers2

4

You have an object at each array location not the string itself, try this instead:

var rates = myArray();
var index, value, result;
var newArr = [];

for (index = 0; index < rates.length; ++index) {
    name = rates[index].name;
    if (name.substring(0, 4) === "Slow") {
        newArr.push(rates[index]);
    }
}

Try using filter function like this, it is much more cleaner to see

var newArr = rates.filter(function(rate){
  return rate.name && rate.name.substring(0,4) === "Slow";
});
sasidhar
  • 7,523
  • 15
  • 49
  • 75
  • 1
    The first 4 characters would be under `substring(0, 4)` – 4castle Jul 23 '16 at 04:10
  • you give value to `name`, then check for `value.substring`, also when `substring(0,5)` returns word with whitespace `"Slow "` so it won't match `"Slow"` – moped Jul 23 '16 at 04:11
  • Yup you are right, my bad. Was editing his code, didn't pay attention. Thanks, edited – sasidhar Jul 23 '16 at 04:12
1

You can use filter to do this, for example:

var newArr = rates.filter(function(val){
    // check if this object has a property `name` and this property's value starts with `Slow`.
    return val.name && val.name.indexOf("Slow") == 0; 
});

As @4castle mentioned, instead of indexOf(...) you can use slice(...) which may be more efficent, eg: val.name.slice(0,4) == "Slow"

Titus
  • 22,031
  • 1
  • 23
  • 33
  • 1
    `indexOf` will look at the whole string. If they just want to look at the first 4 characters, they should use `slice(0, 4) === "Slow"` – 4castle Jul 23 '16 at 04:08