What is the best way to determine the amount of distinct elements in an array of objects based on a specific object property?

I am working with an array called orders.

orders = [
  {table_id: 3, food_id: 5},
  {table_id: 4, food_id: 2},
  {table_id: 1, food_id: 6},
  {table_id: 3, food_id: 4},
  {table_id: 4, food_id: 6},
];

I am looking to create a function that can calculate the number of unique table_ids and food_ids in this array. For example,

For instance,
The unique table_ids in the list are 1, 3, 4 totaling 3.
The unique food_ids in the list are 2, 4, 5, 6 totaling 4

Can anyone guide me on how to accomplish this task?

Answer №1

If you're looking for a solution, here's one that might do the trick:

function findUniqueTableId(orders){
    let uniqueTableId = new Set();
    for(let order of orders){
        uniqueTableId.add(order.table_id);
    }
    return uniqueTableId.size;
}

You can also apply a similar approach to the food_id property in a separate function.

Kudos to @Felix King for coming up with a succinct one-liner using the set object and Array.prototype.map()

let uniqueTableIdCount = new Set(orders.map(x => x.table_id)).size
let uniqueFoodIdCount = new Set(orders.map(x => x.food_id)).size

The .map() method iterates through the array, adds each table_id to the set, and retains only unique values. By chaining methods, we can efficiently determine the size of the set.

Answer №2

I am confident that you have not attempted this yet because the solution is straightforward:

1 - Initialize the arrays

var uniqueIds = [];
var uniqueItems = [];

2 - Iterate through orders and fill the arrays

for (var i = 0; i < orders.length; i++) {
    if (uniqueIds.indexOf(orders[i].id) == -1) // if this ID is not in the unique ID list
        uniqueIds.push(orders[i].id);          // Add the ID to the unique ID list
    if (uniqueItems.indexOf(orders[i].item_id) == -1)  // if this item ID is not in the unique item ID list
        uniqueItems.push(orders[i].item_id);            // Add the item ID to the unique item ID list
}

With your current orders array, the values of uniqueIds and uniqueItems are :

uniqueIds // = [3, 4, 1];
uniqueItems // = [5, 2, 6, 4];

You can also find their lengths :

uniqueIds.length // = 3
uniqueItems.length // = 4

Answer №3

To put it simply:

let uniqueResults = {};

items.forEach(function(order) {
  for (let prop in order) {
    uniqueResults[prop] = uniqueResults[prop] || [];
    if (uniqueResults[prop].indexOf(order[prop]) == -1)
      uniqueResults[prop].push(order[prop]);
  }
})

for (let prop in uniqueResults) {
  console.log("The unique "+ prop +" are "+ uniqueResults[prop] +" with a total count of "+ uniqueResults[prop].length);
}

With only a few lines of code, no need for additional data structures besides the uniqueResults object, no alterations to your current code, and, most importantly, no prior knowledge of the keys in the orders objects required

Answer №4

One way to find the total number of unique values is by adding them to a Set and checking the size of the set.

For those looking for an ES5 compatible solution, it is possible to create a custom set class to achieve the same result.

Answer №5

If you need to generate a list of unique table and food IDs and calculate their occurrences simultaneously, the following piece of code will help you accomplish that task. By executing this code snippet, you will create two objects to store this information...

var orders = [
  {table_id: 6, food_id: 8},
  {table_id: 2, food_id: 3},
  {table_id: 4, food_id: 7},
  {table_id: 6, food_id: 5},
  {table_id: 2, food_id: 7},
];

var tables = {};
var foods = {};

for (var i in orders) {
  var order = orders[i];
  var tableId = "table_id_" + order.table_id;
  var foodId = "food_id_" + order.food_id;

if (tables.hasOwnProperty(tableId)) {
  tables[tableId]++;
  }
  else {
  tables[tableId] = 1;
  }
  
  if (foods.hasOwnProperty(foodId)) {
  foods[foodId]++;
  }
  else {
  foods[foodId] = 1;
  }
}

console.log(tables);
console.log(foods);

To those bothered by my choice of the variable "foods," I must apologize—it's just a bad habit of mine.

Answer №6

To implement a unique filter on an array of objects in TypeScript, you can use a combination of `Array.prototype.sort` and `Array.prototype.filter` methods:

type Order = {
    table_id: number;
    food_id: number;
}

let orders = [
  {table_id: 3, food_id: 5},
  {table_id: 4, food_id: 2},
  {table_id: 1, food_id: 6},
  {table_id: 3, food_id: 4},
  {table_id: 4, food_id: 6},
] as Order[];

let uniqueOrders = orders.sort((a, b) => a.table_id - b.table_id)
    .filter((value, index, array) => index === array.length - 1 || array[index + 1].table_id !== value.table_id);

console.log(uniqueOrders.length); // 3

(code in TypeScript playground)

Answer №7

Task completed!

orders = [
  {table_id: 3, food_id: 5},
  {table_id: 4, food_id: 2},
  {table_id: 1, food_id: 6},
  {table_id: 3, food_id: 4},
  {table_id: 4, food_id: 6},
];

var uniqueTables=[];
var uniqueFoods=[];

for(var i=0; i<orders.length; i++){
  var current=orders[i];
  var tableId = current.table_id;
  var pushTable=true;
  for(var j=0; j<uniqueTables.length;j++){
    if(tableId==uniqueTables[j]){
      pushTable = false;
      break;
    }
  }
  if(pushTable){uniqueTables.push(tableId);}
  
  var foodId = current.food_id;
  var pushFood=true;
  for(var j=0; j<uniqueFoods.length;j++){
    if(foodId==uniqueFoods[j]){
      pushFood = false;
      break;
    }
  }
  if(pushFood){uniqueFoods.push(foodId);}
}
console.log("Unique Tables: " + uniqueTables.length + " Unique Foods: " + uniqueFoods.length);

Answer №8

To extract specific elements, consider utilizing the Set method combined with mapping.

var data = [{ category_id: 3, product_id: 5 }, { category_id: 4, product_id: 2 }, { category_id: 1, product_id: 6 }, { category_id: 3, product_id: 4 }, { category_id: 4, product_id: 6 }], 
    filterUnique = key => [...new Set(data.map(d => d[key]))];
  
console.log(filterUnique('category_id'));
console.log(filterUnique('product_id'));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №9

let ordersList = [
  {tableNumber: 3, foodNumber: 5},
  {tableNumber: 4, foodNumber: 2},
  {tableNumber: 1, foodNumber: 6},
  {tableNumber: 3, foodNumber: 4},
  {tableNumber: 4, foodNumber: 6},
  {tableNumber: 4, foodNumber: 6},
  {tableNumber: 4, foodNumber: 6}
];
  
let tableObject = {}, foodObject = {};
ordersList.forEach(function(order){
  tableObject[order.tableNumber] = null;
  foodObject[order.foodNumber] = null;
});

let uniqueTableNumbers =  Object.keys(tableObject);
let uniqueFoodNumbers = Object.keys(foodObject);

console.log("Unique table numbers: ", uniqueTableNumbers);
console.log("Unique food numbers: ", uniqueFoodNumbers);

Answer №10

data = [
  {user_id: 3, item_id: 5},
  {user_id: 4, item_id: 2},
  {user_id: 1, item_id: 6},
  {user_id: 3, item_id: 4},
  {user_id: 4, item_id: 6},
];
  
function countUniqueItems(arr, key) {
    result = []; 
    arr.map(obj => obj[key])
        .filter(n => result.indexOf(n) <= -1 && result.push(n))

    return result.length;
}

print(countUniqueItems(data, 'user_id'));
print(countUniqueItems(data, 'item_id'));

By the way, the use of && here might seem a bit hacky...

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

What is the best way to transfer information from a server running Express.js to a client using React.js?

When using Express.js, I have the ability to send an HTML file that includes a React component. app.get('/index', function(req, res) { res.sendFile(path.join(__dirname + '/src/index.html')); }); Suppose I want to send a uniqu ...

Tips for implementing JS function in Angular for a Collapsible Sidebar in your component.ts file

I am attempting to collapse a pre-existing Sidebar within an Angular project. The Sidebar is currently set up in the app.component.html file, but I want to transform it into its own component. My goal is to incorporate the following JS function into the s ...

Is it recommended to utilize the useRef hook when storing data that is only initialized once?

When it comes to using react's ref nowadays, things can get a bit confusing. In the past, with class components, the documentation was pretty straightforward. Refs are primarily meant for DOM elements: https://reactjs.org/docs/refs-and-the-dom.html ...

ScriptManager.RegisterClientScriptBlock is failing to execute the already existing script

Background When a client-side button click triggers a server-side function, a loading panel (div) is displayed before the server-side function is executed. The loading panel should be removed once the server-side function completes. My Approach Upon com ...

Mastering form reset functionality using jquery

When attempting to register, an error is generated if any field is left blank in the form (from PHP). The input fields that have been filled out are retained using Smarty: {if isset($smarty.post.registratie.naam)} value="{$smarty.post.registratie.naam}"{el ...

Displaying a progress bar while fetching data in Vue: A step-by-step guide

I am working on developing a progress bar using vue js and bootstrap for my desktop application. Within the template, I have the code that will generate the necessary markup: <div class="container-fluid p-0 vh-100" v-if="isLoading&quo ...

Utilizing SEO and incorporating special characters like !# in a website's URL

I came across an interesting concept about designing a website that utilizes AJAX to load each page section without compromising SEO. It involved incorporating !# in the URL, similar to the approach adopted by Twitter. However, I've been unable to loc ...

What is the best way to display just the selection outcome?

Currently, my code displays a full list of clinics. When I select a province in the dropdown menu, it only shows the clinics located in that specific province. I would like to modify this behavior so that the full list of clinics is not visible initially ...

Is there a way to modify the title of a website upon entering the webpage and then updating it when moving to a new page?

I'm encountering an issue with changing the website title during two specific processes. Upon entering a webpage, the title is modified using the following code: <script type="text/javascript"> $(document).ready(function() { docum ...

What is the best way to extract all of the JSON data from Firebase using a web platform?

As a newcomer to Firebase and noSQL databases, I'm encountering difficulties in extracting all the JSON data from the database. Although I've gone through the firecast tutorials and understand how to retrieve specific values by referencing the da ...

Step by step guide on enabling link routing on a Material UI list item, excluding only one specific button within the list item

I am facing an issue with a component containing ListItem components from material ui. Each ListItem has a button, and the entire listitem should be clickable to route the app somewhere. However, when clicking the delete button, it also routes the app to ...

The functionality of CSS3 animations may sometimes be unreliable following the onLoad event

Here is a snippet of code to consider: $(function() { $('#item').css({ webkitTransform: 'translate(100px, 100px)' }); }); The element I am attempting to move has the following CSS properties: transform: translate3d(0 ...

A guide to examining pixels in Three.js

I have a query about comparing two textures at a pixel level in three.js. I am unsure of how to achieve this as the documentation for Three.js does not provide clear answers, with some classes remaining undocumented. In summary, I am looking to determine ...

Ensuring accurate date formatting of API responses in TypeScript

My REST API returns data in the format shown below:- {"id": 1, "name": "New event", "date": "2020-11-14T18:02:00"} In my React frontend app, I have an interface like this:- export interface MyEvent { id ...

Fade in an image using Javascript when a specific value is reached

Here's the select option I'm working with: <div class="okreci_select"> <select onchange="changeImage(this)" id="selectid"> <option value="samsung">Samsung</option> <option value="apple">App ...

The HttpClient.get('/') request with {observe: 'response'} is failing to retrieve some headers

Currently, I'm in the process of writing an API GET request by utilizing HttpClient.get(). Upon passing in the option to observe the response, I've encountered an issue where accessing the .keys() does not provide me with any headers apart from C ...

Navigating through an Angular 2 service

I'm struggling to retrieve an array from a JSON API and then loop through it. I can't seem to grasp how it all fits together. Any guidance would be greatly appreciated. This is what my service looks like: import {Injectable} from '@angular ...

Guide to using JavaScript to multiply the values from two text fields and showing the result in a separate text field

Here is the code that I am currently using: <script type="text/javascript"> $(function() { $("#addAll2").click(function() { var add = 0; $("#discount") = $dis $(".amt2").each(function() { ...

I found myself puzzled by the error message "Module protobufjs not found."

I am currently utilizing the node library known as node-dota2. I have completed all the necessary steps required by node-dota2, as outlined on this site: https://github.com/Arcana/node-dota2#installation-and-setup 1. Installed it using npm 2. Created a fil ...

Creating a highly innovative server infrastructure tailored for Dojo applications with exceptional features

Recently, I have been using web2py for my projects and have found it incredibly useful in creating RESTful web applications. However, I am now looking to expand my skills in JavaScript by developing a more modern and dynamic client-side application that re ...