MehdiN MehdiN - 1 month ago 9
Javascript Question

How to include elements of an array in another array?

So for example I have a MAIN array with all the information I need:

$scope.songs = [
{ title: 'Reggae', url:"#/app/mworkouts", id: 1 },
{ title: 'Chill', url:"#/app/browse", id: 2 },
{ title: 'Dubstep', url:"#/app/search", id: 3 },
{ title: 'Indie', url:"#/app/search", id: 4 },
{ title: 'Rap', url:"#/app/mworkouts", id: 5 },
{ title: 'Cowbell', url:"#/app/mworkouts", id: 6 }
];


I want to put only certain objects into another array without typing in each of the objects so the end result will look like

$scope.array1 = [
{ title: 'Reggae', url:"#/app/mworkouts",id: 1 },
{ title: 'Cowbell', url:"#/app/mworkouts",id: 6 }
];


I have tried this with no luck:

$scope.array1 = [
{ $scope.songs[1] },
{ $scope.songs[6] }
];


I will have to do a bunch of these so typing in each object would take forever, is there any faster way to do this? Thanks in advance :)

Answer

You need to do something like this:

$scope.array1 = $scope.songs.filter(function (song) {
  return (song.title == "Reggae" || song.title == "Cowbell");
});

Here, the filter function will give you a filtered new array to be replaced for the original scope value.

console

Or in simple way, using the array indices, you can use:

$scope.array1 = [ $scope.songs[0] , $scope.songs[5] ];
Comments