Get a distinct selection of properties in an array of objects using ES6

I have an array of animals:

animals = [
 {name:"Dog", color_id:1, color:"Red" ....},
 {name:"Cat", color_id:2, color: "Blue"....}, 
 {name:"Fish", color_id:3, color:"Purple"...}, 
 {name:Mouse, color_id:2, color:"Blue" ...}
]

My goal is to create a list of unique colors:

colorList = [{value:1, label:"Red"}, {value:2, color:"Blue"}, {value:3, color:"Purple"}] 

I attempted to do this using the following code snippet, but it did not give me the desired results:

animals.forEach(function(currAnimal){
      var i = propertyTypeOptions.findIndex(animals => animals.value == colorList.value);
      if(i <= -1){

        propertyTypeOptions.push({value: currAnimal.color_id, label:  currAnimal.color});
      }
    })

Answer №1

By tracking colors and their corresponding color_ids, we can ensure each color is only added once:

const animals = [
 {name:"Dog", color_id:1, color:"Red" },
 {name:"Cat", color_id:2, color: "Blue"}, 
 {name:"Fish", color_id:3, color:"Purple"}, 
 {name:'Mouse', color_id:2, color:"Blue" }
];
const seenColors = new Set();

const output = animals.reduce((a, { color_id, color }) => {
  if (!seenColors.has(color)) {
    a.push({ color_id, color });
    seenColors.add(color);
  }
  return a;
}, []);

console.log(output);

Answer №2

One technique involves utilizing the reduce method to condense the array into an object. Subsequently, you can utilize Object.values to transform the object back into an array.

let animals = [{"name":"Dog","color_id":1,"color":"Red"},{"name":"Cat","color_id":2,"color":"Blue"},{"name":"Fish","color_id":3,"color":"Purple"},{"name":"Mouse","color_id":2,"color":"Blue"}]

let colorList = Object.values(animals.reduce((c, {color,color_id}) => {
  if (!c[color]) c[color] = {label: color,value: color_id};
  return c;
}, {}));

console.log(colorList);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing directive scope variables to generate dynamic templates

Looking for a solution to dynamically render forms with various controls based on a specific Type value specified in a JSON object. The form will be created based on user input, so the necessary question types may vary. While we will define the types, they ...

Setting response query correctly in Solr using AJAX

Inspired by an example of using Solr's JSON output for AJAX, I have incorporated a drop-down menu into my project form and introduced faceting to the parameters. Parameters: function getstandardargs() { var params = [ 'wt=json' ...

Guide to identifying rows in an array that match a particular month and year

Looking for rows in an array that match a specific month I am faced with the challenge of identifying all rows in an array that have a particular month and year (the first column being a date column). My goal is to extract columns A to I from each of thes ...

Interval set does not refresh an integer

I'm struggling with a function that is supposed to show the number of milliseconds elapsed since Midnight on January 1st, 1970. I've been trying to use setInterval to update the integer every second or millisecond, but it doesn't seem to be ...

Enhance the original array of a recursive treeview in VueJS

After going through this tutorial, I decided to create my own tree view using recursive components in Vue.js. The structure of the input array is as follows: let tree = { label: 'root', nodes: [ { label: 'item1', nod ...

Monitoring user engagement using Socket.io and Firebase

In my Node/Express app, I am working on monitoring active users without using sessions. The app relies on an external API for handling JWT tokens that are directly passed to the client for storing and subsequent API requests. To track active users, I am u ...

Does anyone have an idea of the origin of the item in this ajax .each function?

Currently, I am utilizing the Etsy API with JavaScript by calling this AJAX code: $.ajax({ url: etsyURL, dataType: 'jsonp', success: function(data) { This code returns an object array, if I'm not mistaken. It then proceeds to enter this . ...

Utilize Node.js to compress folders and save them locally by zipping and downloading

Is there a way to zip and download a folder from the path D:/downloads? I have successfully created a folder inside 'downloads' with some dummy content. Now, my next goal is to zip that folder and download it. async downloadFolder(selectedProdu ...

What is the method for specifying a .php page as the html source when using Ext.Panel?

I have a current situation where I manually set the html for an existing panel using a variable in the following way: var htmlContent = '<H1>My Html Page'; htmlContent += '[more html content]]'; var newPanel = new Ext.Panel({ ...

`The value of an array containing specific class elements is lost when accessed within a setTimeout

I've come across an issue while using a JavaScript file to hide several divs all sharing the same class name. The program successfully hides the divs, but when I try to make them visible again after a certain number of seconds, the array of elements b ...

Troubleshooting Axios Error while Sending Data in MERN Stack Application

In my development setup, I'm testing model validation specifically for the length of a name variable. The front-end is configured at http://localhost:3000/ using React + axios, while the back-end utilizes express + node. To enable communication betwe ...

Leveraging jQuery in Content Scripts for Chrome Extensions

I am currently working on developing a Chrome extension that will prompt a small input whenever a user highlights text on a webpage (similar to Medium's feature that allows you to tweet highlighted text). While I am making progress, I believe using j ...

AngularJS: Sending form data to an external server results in an error due to restricted URI access

I am currently diving into the world of AngularJs and putting effort into mastering it. In this process, I've created a demo application that attempts to send form data to a localhost site. The code for this endeavor is provided below. index.html &l ...

Enhance your TypeScript arrays using custom object equality functions

I am looking to utilize array functions such as contains and unique, but I want them to compare equality using my custom equals function. For instance: let arr = [{id:1,..//some more},{id:2,..//some more},{id:3,..//some more}] I need the following code ...

What are the methods for altering the material of a glTF model using THREE.js?

I've created a model using Blender and baked all the lighting and textures. However, when I import it into THREE.js in .glb format, it automatically uses the standard material. While this may work in certain cases, my concern is that I want to retain ...

The pagination of SESSION Arrays does not automatically halt once all the arrays have been exhausted

I have a PHP Page where I am displaying my SESSION's arrays using pagination. Each page shows ten arrays, but my session currently holds eleven arrays. The issue arises when I navigate to the second pagination page with the eleventh array; it starts d ...

"Enhance Your Search Input with Dynamic Suggestions from JSON Data Integrated with

Hello! I am looking to create an autosuggest feature using a PHP file that returns a JSON Object. I then parse it in JavaScript to generate a link with the correct ID (refer to the provided JSON data). JSON data from search_new.php: {"Data":{"Recipes":{ ...

Merge dates and values seamlessly in Google Sheets

In my Google Sheet, I have columns for DepositReceived, DepositPaid, BalanceReceived, and BalancePaid. Each metric has a date column and a value column. DepositRecievedDate DepositReceivedValue DepositPaidDate DepositPaidValue BalanceReceivedDate Balance ...

PHP: Ensuring only one date occurrence within a multi-dimensional array

I am working with an array that contains brand_ids and dates of sales within each brand. The dates may be repeated for different products within the same brand_id. Here is an example of my array: array:5 [▼ 2 => array:3 [▼ 0 => "2022- ...

Exception thrown when accessing an index outside the range of an array

I'm having trouble printing out the elements of this multidimensional array as I keep encountering an index out of range error. public class test { public static void main(String[] args) { int array1[][]={{1,2,3,4},{5},{6,7}}; for ...