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
1

6 Answers 6

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)

Sign up to request clarification or add additional context in comments.

Comments

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)
   

Comments

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);

Comments

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.

Comments

0

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


Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.