Generate a fresh object if the values within the TypeScript object are identical

How can I filter an object to return a new object containing elements with the same values?

For example:

allValues = {"id1": 3, "id2": 4, "id3": 3}

The desired output is:

filteredValues = {"id1": 3, "id3": 3}

This is because the keys "id1" and "id3" have the same value.

The resulting object will only contain 3 keys and values. If no values are shared, an empty object should be returned. Any solutions?

Answer №1

With the consistent presence of 3 data in the object,

I find it more convenient to manually compare them.

const IsSame = (...data) => {
  return data.every((value, _, array) => value === array[0])
}

const Process = (raw) => {
  const keys = Object.keys(raw)
  const values = Object.values(raw)

  const value = values[0]

  if (IsSame(values[0], values[1], values[2])) return {
    [keys[0]]: value,
    [keys[1]]: value,
    [keys[2]]: value,
  }

  if (IsSame(values[0], values[1])) return {
    [keys[0]]: value,
    [keys[1]]: value,
  }

  if (IsSame(values[0], values[2])) return {
    [keys[0]]: value,
    [keys[2]]: value,
  }

  if (IsSame(values[1], values[2])) return {
    [keys[1]]: value,
    [keys[2]]: value,
  }

  return {}
}

const raw = {
  "id1": 1,
  "id2": 0,
  "id3": 1
}

const result = Process(raw)

console.log(result)

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

There was an issue with the v-on handler: "An error occurred because it was unable to read properties of an undefined value (specifically 'input')."

Can anyone help me? When I click the icon inside the avatar, I want to select a file. But I'm getting an error: Error in v-on handler: "TypeError: Cannot read properties of undefined (reading 'input'). Could anyone help me? <v-row v-for=" ...

Application unable to save data to file with no indication in error logs

Recently, I've been experimenting with the Capture-Website package, which is designed to save website screenshots to a file. Initially, everything was working smoothly until I decided to restart the server. Now, although my code is running without a ...

Executing the npm run test command with the unsafe-perm flag within the lifecycle phase

My React/Redux app is working fine, but whenever I run the command below: npm run test An error occurs as shown below: 6 info lifecycle [email protected]~test: [email protected] 7 verbose lifecycle [email protected]~test: unsafe-perm in li ...

Saving fonts when deploying on Vercel with Next.js is not supported

Troubleshooting Differences in Local Viewing and Deployment: https://i.stack.imgur.com/jktPN.png When viewing locally, everything appears as expected. However, upon deploying, there are noticeable discrepancies. https://i.stack.imgur.com/NKQQ6.png Even ...

Searching for elements in Selenium using JavaScript's equivalent of findElement(by.className)

I need to locate an id tag within a class tag on an html page. driver.find_element(By.XPATH, "//div[@class='Content warning']/p").get_attribute("id") https://i.stack.imgur.com/NlU8t.png I successfully accomplished this with ...

When a user scrolls over an element with a data-attribute,

Looking to create a dynamic header effect on scroll? I have two headers, menu1 by default and menu2 hidden with display:none. In specific sections of my website, I've added a special attribute (data-ix="change-header") to trigger the header change. T ...

Having trouble with updating React state? The useEffect hook runs when attempting to change the state, but it seems to have the

Having worked with useEffect and its ability to trigger after a state variable has been updated, I am well-versed in its functionality. I'm currently drafting this post on my phone while away from home. Here's the setup I have: const [dateValue ...

React automatic scrolling

I am currently working on implementing lazy loading for the product list. I have created a simulated asynchronous request to the server. Users should be able to update the page by scrolling even when all items have been displayed. The issue arises when ...

Adding a fresh element to an object array in TypeScript

How can we add a specific value to an array of objects using TypeScript? I am looking to insert the value 1993 into each "annualRentCurrent" property in the sample object. Any suggestions on how to achieve this in TypeScript or Angular? Thank you! #Data ...

The Art of JavaScript Module Patterns in Image Sliders

I'm diving into the world of JavaScript and decided to try my hand at creating an image slider. I managed to put together a basic version by following a couple of tutorials, and although it's working fine, I want to move it to an external js file ...

Issue with button events not being triggered while working with dynamically created classes

I am facing an issue with three plus (+) buttons that are next to three separate tables built using DataTables. The problem arises because all the plus buttons were created in one location with DataTables, resulting in them being assigned the same classes ...

The Vue.js @click event does not function properly when used in a selection on mobile

I designed a dropdown menu with different options, and when one is selected it updates the "Value" in vue to a specific amount. Then, I display the selected amount in an input field. For example: <select class="form-control" style="max-width: 150px;" ...

Values are being set back to '1' within the popup dialog

After recently incorporating Twitter Bootstrap into my web app project, everything seemed to be going smoothly until I encountered an issue with a modal window. Following the Bootstrap documentation, I set up a button that triggers a modal window to appea ...

Jest identifies an open handle when working with an Express application

For quite some time now, I've been grappling with a particular issue. It all started when I was conducting basic integration tests using a MongoDB database. However, I've minimized the code to its simplest form. The only thing left running is a s ...

What could be causing the invalid hooks error to appear in the console?

I'm completely stumped as to why this error is popping up when I try to use mutations with React Query. Any insights or advice would be greatly appreciated. Note: I'm implementing this within a function component in React, so it's puzzling ...

The image slider script I've built is functioning perfectly in Codepen, but unfortunately, it's not working as

My image slider called Orbit is functioning properly on Codepen.io, however when I try to run the exact same code on Plunker, it doesn't work at all. <ul class="slider" data-orbit> <li> <img src="http://foundation.zurb.com/docs/a ...

Guide to organizing the legend section into two columns within Apache Echarts

I'm looking to customize the legend area layout in Apache Echarts for a two-column display. Can anyone provide guidance on achieving this using legend options? I have been unable to locate any examples demonstrating this particular layout. For refere ...

Problem with jQuery's .prepend method being called twice on list items

Looking to enhance the appearance of a list by adding some icons before the anchor links within each list item. <ul class="submenu-children"> <li><a href="#">Link</a></li> <li><a href="#">Link</a></li> ...

Tips for integrating Excel files with NestJS

I'm in the process of developing a REST API that will utilize a third-party API to retrieve specific status information. The URLs needed for this API are stored in an Excel file, which is a requirement for this use case. My goal is to extract the URLs ...

The order in which JavaScript files are loaded is critical, especially when dealing with external

After experiencing issues with my script not working because it was loaded before jQuery by the client (a necessity), I am seeking a solution. My challenge lies in ensuring that my code waits for jQuery to load before execution, especially when dealing wi ...