Reputation: 27
So I have this array and I want to make a new array with those objects that have the swimming value in sports.
var watchesArray = [
{
model: "Swim",
image:"",
price: 149.99,
sports:["Swimming", "Running"]
},
{
model: "FR 10",
image:"",
price: 129.99,
sports:["Running"]
},
{
model: "FR 15",
image:"",
price: 199.99,
sports:["Running"]
},
];
So far I have this but I dont know how to add on to the sliced array with each go around in the for loop. How should I do this?
for (var i = 0; i < watchesArrayLength; i++) {
if (watchesArray[i].sports.indexOf("Swimming") > -1) {
var runningWatchArray = watchesArray.slice(i);
}
}
Upvotes: 0
Views: 50
Reputation: 234
You could also use forEach to loop through each item of the watchesArray...
var runningWatchArray = new Array();
watchesArray.forEach(function(watch){
if (watch.sports.indexOf("Swimming") > -1) {
runningWatchArray.push(watch);
}
}
Upvotes: 0
Reputation: 2986
You can use .filter() method:
watchesArray = [...];
var result = watchesArray.filter(function(watch) {
return watch.sports.indexOf('Swimming') !== -1;
});
Upvotes: 4
Reputation: 10979
If I understand correctly, what you want is
var runningWatchArray = [];
for (var i = 0; i < watchesArrayLength; i++) {
if (watchesArray[i].sports.indexOf("Swimming") > -1) {
var watch = watchesArray.slice(i);
runningWatchArray.push(watch);
}
}
Upvotes: 0