Chris Maher
Chris Maher

Reputation: 7

How to filter Javascript array of Objects to distinct values of one Column

I have a Javascript array of "Album" objects which holds data such as Album Title, Year, Artist, Description

Id like to create a new String Array that holds just the distinct years.

Ive tried a unique pipe from

https://www.npmjs.com/package/ng2-pipes#installation

But have no luck.

My goal is to have a "Filter by year" dropdown which takes a string array of unique years

import {NgPipesModule} from 'ngx-pipes';

<button ngbDropdownItem *ngFor="let album of filteredAlbumListYear | unique " [value]="">{{album.Year}}</button>

Im getting

2019
2019
2019
2019
2018
2018
2017

In the dropdown where i just want

2019
2018
2017

Upvotes: 0

Views: 775

Answers (6)

Shrinivasan
Shrinivasan

Reputation: 281

Here is an alternate solution.

 arr = [2019,2019,2019,2019,2018,2018,2017];
 uniqueArray = arr.reduce((unique,item)=>unique.includes(item)?unique:[...unique,item],[])
 console.log(uniqueArray)

Upvotes: 0

Saurabh Yadav
Saurabh Yadav

Reputation: 3386

You can use Set to allow only unique and Spread syntax

     let list = [2019,2019,2019,2018,2018,2017]; 
     let result = [...new Set(list)]; 
     console.log(result)
   

Upvotes: 1

mithu
mithu

Reputation: 1

var array=[2019,2019,2019,2018,2018,2017]; array =array.filter((year,index)=>array.indexOf(year)===index); console.log(array);


Upvotes: 0

Johns Mathew
Johns Mathew

Reputation: 812

You can use a Set in javascript to store unique values. Irrespective of the number of times you push an item to the set, it would only have a single copy.

If your filteredAlbumListYear is an array containing years alone, then you can create a new Set directly from filteredAlbumListYear.

this.filteredAlbumListYear = [...new Set(this.filteredAlbumListYear)]

This would create a new Set from the years, convert it into an Array and assign back to filteredAlbumListYear.

OR you can create a new array directly from your Album list.

const uniqueYearsSet = new Set();
this.albums.forEach(album => this.uniqueYears.add(album.year));
this.uniqueYears = [...uniqueYearSet];

and then use uniqueYears in your *ngFor loop.

Upvotes: 0

Pushprajsinh Chudasama
Pushprajsinh Chudasama

Reputation: 7949

Try this code. it will helps you.

     arr = [2019,2019,2019,2019,2018,2018,2017];
     uniqueArray = Array.from(new Set(arr));
     console.log(uniqueArray)

Upvotes: 1

Rushi Patel
Rushi Patel

Reputation: 601

In Javascript, you can follow the below code

  array= [2019,2019,2019,2018,2018,2017]; 
  const newArray = this.array.filter((year,index)=> this.array.indexOf(year)===index);
  console.log(newArray);

Upvotes: 0

Related Questions