Solved

es6 typescript how to filter an array

Posted on 2016-11-01
10
39 Views
Last Modified: 2016-11-06
Hi
i have a libraries array, and an albums array. an album can belong to one or more libraries. for each library i have a get album button, which suppose to bring all the albums that belong to that specific library.
 
so i have this albums array ( for the moment it is all hard coded, eventually i will use firebase):
  private albums: Album[] = [
    new Album(
      '4TV-007 Commercials',
      "/assets/images/albums/4TV-7.jpg",
      [
        "4TV Producers"
      ]
    ),
    new Album(
      '4TV-008 Restaurants',
      "/assets/images/albums/4TV-8.jpg",
      [
        "4TV Producers",
        "1M1 Music"
      ]
    ),
    new Album(
      '4RP-012 Urban Radio',
      "/assets/images/albums/4RP_12.jpg",
      [
        "1M1 Music"
      ]
    ),
    new Album(
      '4RP-013 Latin Radio',
      "/assets/images/albums/4RP_13.jpg",
      [
        "4Radio Producers"
      ]
    ),
  ];

Open in new window


the inner arrays are the libraries names . so now i need to filter and return only the albums that belongs to the library. this is my method, i am passing the library name. obviously just one library name:
  getAlbumsByLibrary(lib: string){
    
    for(let album of this.albums){
      //console.log(album.libs);
      return this.albums.filter( albums => album.libs === lib);
    }
  }

Open in new window


the issue is that i get all the inner arrays. i need to return albums that belong to the passed library name.
0
Comment
Question by:derrida
  • 5
  • 3
  • 2
10 Comments
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41868188
so i have this albums array ( for the moment it is all hard coded, eventually i will use firebase):
If Firebase is your ultimate goal then why are you bothering with Array filtering - makes more sense to put it into Firebase and then use Firebase to do the filtering for you.

Each album has a library ID that identifies which Library it belongs to.

You then do a query against the Firebase libraries node for all libraries that have an album matching that id.
0
 
LVL 1

Author Comment

by:derrida
ID: 41868282
hi Julian
yeah, that what i thought too. but i'm used to relational databases, using tables and joins. but i understood that in firebase there are no joins and so on.
so i thought maybe start with basic arrays and from there i'll get an idea how to structure the relationships.

so if i have libraries, which contain albums ( each album can belong to several libraries ), and each album contain tracks ( and each track can belong to several albums ).

now i read that it is bad practice on firebase to over nest, but then i'm not sure how to make a schema on firebase.

how would you go about it?

best regards
0
 
LVL 27

Expert Comment

by:BigRat
ID: 41868545
I don't know about TypeScript but in simple Javascript the code ought to be
function getAlbumsByLibrary(lib: string) {
    var newArray = for(let album of this.albums){
      //console.log(album.libs);
      return this.albums.filter( albums => album.libs === lib);
    }
   return newArray;
  }

Open in new window


https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

or am I missing something?
0
 
LVL 1

Author Comment

by:derrida
ID: 41869646
hi BigRat
with your code visual studio code underline the for with the message an expression expected ( i believe it's a typings thing ) and the equation thing say:
Operator '===' cannot be applied to types 'any[]' and 'string'.

which makes sense since it compare the inner array with the passed string.
0
 
LVL 27

Expert Comment

by:BigRat
ID: 41870015
OK, how about just two =s?
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 1

Author Comment

by:derrida
ID: 41871760
same results.
0
 
LVL 51

Accepted Solution

by:
Julian Hansen earned 500 total points
ID: 41871975
Still think FB might be the right place to do this but I have not managed to put together a sample for that yet

I am wondering if filter is what you are looking for here

Lets break down what you are doing.

You have an array of Albums.
You want to search a property of each album (which is an array of strings) for a specific string.

The filter as you have it is not going to work because you are trying to filter based on

album.libs == lib - you are comapring an array to a string instead of checking to see if the lib is included in the array album.libs

Try this instead
    getAlbumsByLibrary(lib: string){
        return this.albums.filter(function(album:Album){
            for(let entry of album.libs) {
                if (entry == lib) return true
            }
            return false;
        });
    }

Open in new window


Full source
class Album {
  albumname: string;
  path: string;
  libs: Array<string>;
	constructor (albumname, path, libraries){
		this.albumname = albumname;
		this.path = path;
		this.libs = libraries;
	}
}

class Music {
private albums: Album[] = [
        new Album(
        '4TV-007 Commercials',
        "/assets/images/albums/4TV-7.jpg",
        [
            "4TV Producers"
        ]
    ),
	new Album(
	  '4TV-008 Restaurants',
	  "/assets/images/albums/4TV-8.jpg",
	  [
		"4TV Producers",
		"1M1 Music"
	  ]
	),
	new Album(
	  '4RP-012 Urban Radio',
	  "/assets/images/albums/4RP_12.jpg",
	  [
		"1M1 Music"
	  ]
	),
	new Album(
	  '4RP-013 Latin Radio',
	  "/assets/images/albums/4RP_13.jpg",
	  [
		"4Radio Producers"
	  ]
	)
];

    getAlbumsByLibrary(lib: string){
        return this.albums.filter(function(album:Album){
            for(let entry of album.libs) {
                if (entry == lib) return true
            }
            return false;
        });
    }
}

let lib = new Music();
var x = lib.getAlbumsByLibrary('4TV Producers');
console.log('Result');
console.log(x);

Open in new window

0
 
LVL 1

Author Closing Comment

by:derrida
ID: 41875910
this worked.

now regarding firebase, Julian, would you say thi is a good schema for the database? if so how can I make a "join" on those "tables"?

{
  "Tracks" : [ null, {
    "albums" : {
      "4RP-012 Urban Radio" : true,
      "4RP-013 Latin Radio" : true
    },
    "categories" : {
      "dance" : true,
      "electronica" : true,
      "pop" : true,
      "r&b" : true,
      "urban" : true
    },
    "composers" : {
      "ASCAP" : true,
      "BMI" : true,
      "Danny Balis" : true,
      "Dusty Hendrix" : true,
      "Jeffrey W Wade" : true,
      "John Holt" : true,
      "Ruben Ayala" : true
    },
    "description" : "magic dance the pop for type sassy",
    "duration" : "01:00",
    "instruments" : {
      "drum percussion machine" : true,
      "keyboard synthesizer" : true
    },
    "made_for" : "magazine film movie tv daytime fashion showbiz",
    "pace" : "128 medium fast",
    "styles" : {
      "driving motion" : true,
      "floating motion" : true,
      "sexy" : true
    },
    "title" : "Looking For You",
    "track_number" : "01"
  } ],
  "albums" : [ null, {
    "imagePath" : "/assets/images/albums/4RP_12.jpg",
    "libs" : {
      "1M1 Music" : true
    },
    "title" : "4RP-012 Urban Radio"
  }, {
    "imagePath" : "/assets/images/albums/4RP_13.jpg",
    "libs" : {
      "4Radio Producers" : true
    },
    "title" : "4RP-013 Latin Radio"
  }, {
    "imagePath" : "/assets/images/albums/4TV-7.jpg",
    "libs" : {
      "4TV Producers" : true
    },
    "title" : "4TV-007 Commercials"
  }, {
    "imagePath" : "/assets/images/albums/4TV-8.jpg",
    "libs" : {
      "1M1 Music" : true,
      "4TV Producers" : true
    },
    "title" : "4TV-008 Restaurants"
  } ],
  "libraries" : [ null, {
    "imagePath" : "/assets/images/libraries/4TV-Producers.jpg",
    "name" : "4TV Producers"
  }, {
    "imagePath" : "/assets/images/libraries/4Radio-Producers.jpg",
    "name" : "4Radio Producers"
  }, {
    "imagePath" : "/assets/images/libraries/1M1-MARK-PETRIE-MUSIC-logo-300c.jpg",
    "name" : "1M1 Music"
  } ]
}
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41875939
It's a tricky one. According to the FB docs the idea is to create indices in each of the linked items so
Albums has an index of tracks
Tracks has an index of albums.

Which means duplication with every operation you need to maintain the value in two places.

Busy with a similar project at the moment - will post back when I make some progress.
0
 
LVL 1

Author Comment

by:derrida
ID: 41875944
cool :)
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Having worked on larger scale sites, we found out that you are bound to look at more scalable solutions to integrating widgets, code snippets or complete applications and mesh them into functional sites, in any given composition. To share some of…
JavaScript can be used in a browser to change parts of a webpage dynamically. It begins with the following pattern: If condition W is true, do thing X to target Y after event Z. Below are some tips and tricks to help you get started with JavaScript …
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now