0

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
Bill P
  • 3,622
  • 10
  • 20
  • 32

6 Answers6

1

Try this code. it will helps you.

     arr = [2019,2019,2019,2019,2018,2018,2017];
     uniqueArray = Array.from(new Set(arr));
     console.log(uniqueArray)
Pushprajsinh Chudasama
  • 7,772
  • 4
  • 20
  • 43
1

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)
   
Saurabh Yadav
  • 3,303
  • 1
  • 10
  • 20
0

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);
Rushi Patel
  • 561
  • 4
  • 14
0

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.

Johns Mathew
  • 804
  • 5
  • 6
0

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


mithu
  • 1
  • 4
0

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)
Shrinivasan
  • 261
  • 4
  • 9