Exploring a TypeScript Object to uncover a desired value

Searching for the correct key in the object that corresponds to the value "1".

The function currently outputs undefined, which is the intended behavior.

input : deliveryIds: [5,4,5,3,3]
output: 4

This code snippet aims to find the missing quad by iterating through the Object.

I would greatly appreciate any assistance on what modifications need to be made.

function findMissingQuad(deliveryIds: number[]) {
  const idsToOccurrences = {};

  deliveryIds.forEach(id => {
    if (idsToOccurrences[id]) {
      idsToOccurrences[id]++;
    } else {
      idsToOccurrences[id] = 1 || [];
    }
  });

  return Object.keys(idsToOccurrences).forEach(id => {
    if (idsToOccurrences[id] === 1) {
      return id;
    }
  });
}

Answer №1

To address this issue, one approach would be to maintain two sets of numbers: one for keeping track of all seen numbers and another for storing numbers that have only been seen once. If a number is encountered again, it is removed from the set of numbers seen just once:

function findMissingQuad(deliveryIds/*: number[]*/) {
    const seen = new Set();
    const once = new Set();
    for (const id of deliveryIds) {
        if (seen.has(id)) {
            // We've seen this one before
            once.delete(id);
        } else {
            // First time we've seen this one
            seen.add(id);
            once.add(id);
        }
    }
    return [...once];
}

console.log(findMissingQuad([5, 4, 5, 3, 3]));
console.log(findMissingQuad([5, 4, 5, 2, 3, 3]));

It's worth noting that the function returns an array to account for scenarios like the second example provided, where there may be multiple unique values in the list.

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

Updating the page dynamically in React/Redux by making API calls based on user submissions

My current task involves calling an API with Redux, triggering the call based on a form submission. If the query is empty, it should return all lists; otherwise, it should only return lists that match the query. // List.tsx import React, { useEffect, useS ...

What is the process of using 'DefaultImports' to import DTOs into TypeScript through ServiceStack?

Whenever I attempt to utilize the command line tools that come with ServiceStack for TypeScript, I continuously encounter issues with the DefaultImports functionality not behaving as anticipated or being particularly beneficial. What is the proper way to m ...

Having difficulty in converting JSON objects into key/value pairs in Angular 7

I have a task to convert my JSON data from its current format as shown below: cacheMapDataDto = [{ "cacheName": "cache_nchl_individual_type", "count": 2, "mapObj": { "NCHL_BI_BATCH_VERIFICATION": false, "NCHL_STL_BATCH_VERIFICATIO ...

A guide on converting JSON to TypeScript objects while including calculated properties

I have a standard JSON service that returns data in a specific format. An example of the returned body looks like this: [{ x: 3, y: 5 }] I am looking to convert this data into instances of a customized TypeScript class called CustomClass: export class ...

What is the best way to implement a switch case for the value of a property within an object in a TypeScript file?

The object I'm dealing with looks like this: {a: auth?.type === '1' || auth?.type === '2' || auth?.type === '3' ? { reason: // I need to implement a switch case here : un ...

"Upon the addition of a child, no response is being given

My database structure resembles the following: https://i.sstatic.net/duWdk.png /* formsById formId usersList userId */ I am trying to retrieve a list of all users (usersList) associated with a specific formId. Below is my method ...

ESLint does not recognize the types from `@vuelidate/core` when importing them

When working with TypeScript, the following import statement is valid: import { Validation, ValidatorFn } from '@vuelidate/core' However, this code triggers an error in ESLint: The message "ValidatorFn not found in '@vuelidate/core' ...

Error message: Issue with TypeScript and cleave.js - 'rawValue' property is not found on type 'EventTarget & HTMLInputElement'

I am encountering an error with the onChange event while implementing cleave in typescript. TypeScript is throwing an error indicating that 'rawValue' is not present in event.target. Here is my code: import React, { useCallback, useState, useEff ...

How can I retrieve the number of events remaining after removing one in Protractor's end-to-end automation?

I am in need of testing the removal of an event and confirming that it has been successfully removed. Since these events are not unique and can vary in number during testing, I believe using a count would be the most suitable approach. This is all new to ...

Converting an array of objects to an array of JSON objects in TypeScript

My dilemma lies in the data I have uploaded under the _attachments variable: https://i.sstatic.net/jnFNH.png My aim is to format this data for insertion in the following structure: "_attachments": [ { "container": "string", "fileName": "string" ...

The class field remains unset

I'm currently developing my own custom CQRS library and I've encountered an issue where a specific field is not being set correctly. The problem appears to be within classes that extend my AggregateRoot abstract class. Take a look at the followin ...

Customizing key values within nested objects in Angular2: A comprehensive guide

I need assistance with setting up a JSON object for a post in Angular2/Typescript. I am trying to dynamically set the nested object values for a key. Is it possible to achieve this using Angular2/Typescript? I have attempted to retrieve the values from JS ...

The parent component's state does not reflect updates made by the child component's successful dispatch of a reducer through Redux Toolkit

I encountered a strange issue where the state slice is behaving correctly (verified by unit tests and manual testing). However, it appears that the react selector is not properly subscribing to it. Here is the parent component code: import { useSelector } ...

Having trouble executing the project using Gulp

I'm a beginner in front-end development and I am working on an existing project that I'm having trouble running. According to the documentation, I should run the project by executing: $ gulp && gulp serve But I keep getting this error: ...

NG8003 error: ExportAs 'ngForm' directive not found in the system

I encountered an issue with my first Angular 11 project: No directive found with exportAs 'ngForm'. Despite importing FormsModule and ReactiveFormsModule in app.module.ts, the error persists. Here is the code snippet: This is from product.compon ...

Can a package be published with an ambient module declaration?

Currently, I am dealing with a package that contains numerous generated modules all exporting the same type, such as an icon library. I am trying to avoid the tedious task of creating individual .d.ts files for each module since they would essentially be ...

Transferring data between components in Ionic 2: Service to Page

My service code includes two functions - one for creating a native storage with IP and port, and the other for retrieving values from the native storage. DatabaseService export class DatabaseService { ... public ip: string; public port: string; . ...

What is the correct way to implement TypeScript with Array.prototype.reduce?

I am facing a challenge with my reduce function and I have tried multiple solutions without success: interface ITask { id: string; was: string; } //sampleData: const tasks = [ {id: "a", was: "Foo"}, {id: "b", was: & ...

The resolver function in the Nextjs higher order API is not defined

I am trying to create a custom wrapper function for my NextJs API routes that will verify a JWT in the request, validate it, and then execute the original API handler. Here is how I have defined my wrapper function: interface ApiError { message: string, ...

Sending data to child components in Ionic

I am currently utilizing Ionic's router-outlet to navigate between a parent page and three children pages: parent.page.html <ion-content> <ion-router-outlet></ion-router-outlet> </ion-content> parent-routing-module.page.t ...