Home > Blockchain >  Filter and get unique values from array
Filter and get unique values from array

Time:10-12

I am trying to apply filter on array and get unique values. In the array below, I am applying filter on Group and then extract unique values from Category. I have written a function which is working absolutely fine, wanted to understand if it is an efficient approach to pull unique values after filtering.

var myList = [
    { "Fund": "Baroda Credit Risk Fund Plan B Direct Growth", "Group": "Equity", "Category": "ABCD", "Category Rank": 1 },
    { "Fund": "Baroda Credit Risk Fund Plan B Direct Growth", "Group": "Debt", "Category": "Credit Risk", "Category Rank": 1 },
    { "Fund": "Baroda Credit Risk Fund Plan B Direct Growth", "Group": "Equity", "Category": "XYZ", "Category Rank": 1 },
    { "Fund": "Baroda Credit Risk Fund Plan B Direct Growth", "Group": "Equity", "Category": "XYZ", "Category Rank": 1 }
]


function getUnique(myList, searchTerm) {

    // Filtering on 'Group' variable;   
    var data_filter = myList.filter(element => element.Group == searchTerm);

    // Get values of CategoryList;
    var CategoryList = [];
    data_filter.forEach(item => {
        a = item.Category;
        CategoryList.push(a);
    });

    // Unique values of CategoryList and then sort;
    var newarr = CategoryList.filter((x, y) => CategoryList.indexOf(x) == y).sort();

    return (newarr);

}

console.log(getUnique(myList, "Equity"))

CodePudding user response:

You could make use of Set.

Your filter logic to filter down the input array is correct. In order to generate the unique categories, you could create an array of categories using Array.map. From that list you can pick the unique elements using Set. Also sort that unique array if needed.

Working Fiddle

var myList = [
  { "Fund": "Baroda Credit Risk Fund Plan B Direct Growth", "Group": "Equity", "Category": "ABCD", "Category Rank": 1 },
  { "Fund": "Baroda Credit Risk Fund Plan B Direct Growth", "Group": "Debt", "Category": "Credit Risk", "Category Rank": 1 },
  { "Fund": "Baroda Credit Risk Fund Plan B Direct Growth", "Group": "Equity", "Category": "XYZ", "Category Rank": 1 },
  { "Fund": "Baroda Credit Risk Fund Plan B Direct Growth", "Group": "Equity", "Category": "XYZ", "Category Rank": 1 }];

function getUnique(myList, searchTerm) {
  // Filtering on 'Group' variable;   
  const data_filter = myList.filter(element => element.Group == searchTerm);
  const CategoryList = [...new Set(data_filter.map(item => item.Category))];
  return CategoryList.sort();
}

console.log(getUnique(myList, "Equity"));

  • Related