If the objects share the same identification number, then add them to a separate array

I'm on the path to creating a new object where names are grouped together based on matching IDs. The solution isn't perfect yet, but progress is being made.

const names = [
{id:1,name:"jame"},
{id:2,name:"jill"},
{id:3,name:"hanna"},
{id:3,name:"clark"}
]

const newNames = []
// Working towards this goal
names.foreach((person,index) => {
 if(newNames[index].id === person.id){
 newNames.push({id:person.index, names:[...newNames.name,person.name]})
 }else{
 newNames.push({id:person.index, person.name})
 }
})

The desired result would resemble this:

const newNames = [
{id:1,name:"jame"},
{id:2,name:"jill"},
{id:3,names: {name:"clark",name:"hanna"}}
]

Encountered Issue: Cannot read properties of undefined (reading 'id')

Answer №1

Here is one approach to tackle the problem:

const people = [
    {id:1,name:"jame"},
    {id:2,name:"jill"},
    {id:3,name:"hanna"},
    {id:3,name:"clark"}
];

let result = []
let ids = [...new Set(people.map(i=>i.id))];
ids.forEach((id) => {
    let res = people.filter((person) => person.id == id)
    result.push({id, name: res.length > 1 ?
        res.map(i => i.name) :
        res[0].name})
})
console.log(result)

It is worth noting that an array is used for the name attribute when there are multiple names to avoid redundancy.


Expanding on the provided solution:

people.forEach((person,index) => {
    let existingIndex = newItems.findIndex( (entry) => entry.id === person.id)
    if(existingIndex >= 0){
        if(newItems[existingIndex].hasOwnProperty('name'))
            newItems[existingIndex] = ({id: person.id, names: [newItems[existingIndex].name,person.name]})
        else
            newItems[existingIndex] = ({id: person.id, names: [...newItems[existingIndex].names,person.name]})
     } else {
        newItems.push({id:person.id, name: person.name})
      }
})

The snippet newItems[index].id in your original code triggers an error as newItems is currently empty. Therefore, newItems[0] resolves to undefined.

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 are effective ways to eliminate script tags from a webpage?

I have implemented tags on my website that users can use to interact with the site. My goal is to figure out how to make the browser only read text from a specific file I write, without any HTML. This should be restricted to certain sections of my websit ...

Having trouble executing react-native project using the command "npx react-native run-android"

Hey there! I've been working on a react-native project for quite some time now and everything was going smoothly until yesterday. I encountered an error when running the command npx react-native run-android in Metro before the project had fully execut ...

Why are my functions still being called asynchronously? I must be missing something

My task involves downloading 5 files exported from our school's database and running a query based on the first export. There will be queries for the other four files, and since there are three schools, my functions need to be scalable. I have two fu ...

Ngrx/effects will be triggered once all actions have been completed

I've implemented an effect that performs actions by iterating through an array: @Effect() changeId$ = this.actions$.pipe( ofType(ActionTypes.ChangeId), withLatestFrom(this.store.select(fromReducers.getAliasesNames)), switchMap(([action, aliases ...

Exploring the advanced features of OpenOffice Draw for improved geometry analysis

Struggling with the draw:enhanced-geometry section that involves draw:enhanced-path and draw:equation. I'm working on an OOo converter but can't seem to find any concrete solutions or extensive documentation about this part. Any suggestions on ho ...

What is the best way to display a message on the 403 client side when an email sending fails?

I am attempting to display an alert message when the email is sent successfully or if it fails. If it fails, I receive a 403 status code from the backend. However, I am unsure how to handle this error on the client-side. In the case of success, I receive a ...

I am having issues with the accuracy of my JavaScript number validation function

function CheckIfNumeric() { var quantity = jQuery("#txtShippedQuantity").val(); quantity = quantity.toString(); for (i = 0; i < quantity.length; i++) { var character = quantity.charAt(i); if (isNaN(character)) { ...

Tips for fixing a shader issue with a custom hover state shader on an image component in a React project utilizing react-three-fiber

I am currently working on implementing an image component with a hover effect using shaders in react-three-fiber. The shader I'm using was originally created by TheFrost and it can be found at https://codepen.io/frost084/full/OKZNRm. However, I am e ...

Angular directive compatibility with Mozilla Firefox

I've encountered a strange issue with my directive in Firefox. The directive is designed to limit user input, and it functions correctly in Chrome. However, in Firefox, once the user reaches the input limit, they are unable to delete any characters - ...

Difficulty triggering an event within a collection in Backbone.js

Having recently delved into JavaScript and Backbone, I encountered a puzzling error. Router = Backbone.Router.extend({ routes: { ":albumID": "load" }, load: function (albumID) { if (controller.collectionInitialized == true) ...

There was a TypeError encountered in a Node application, stating: "Unable to access the 'trim' property of an undefined

Currently, I am developing a JavaScript application that follows the MVC model. In the controllers, there is a userController.js file, and in the models, there is a user.js file which contains a cleanup function. However, I am encountering a TypeError: Can ...

Unusual Behavior in AngularJS: Using ng-include Triggers Full Page Reloading

An issue arises where a simple ng-include command causes the entire website to be printed recursively in a specific area of the page, ultimately crashing the browser. Even changing the path doesn't resolve the problem, suggesting that it's not ev ...

Executing a function within the same file is referred to as intra-file testing

I have two functions where one calls the other and the other returns a value, but I am struggling to get the test to work effectively. When using expect(x).toHaveBeenCalledWith(someParams);, it requires a spy to be used. However, I am unsure of how to spy ...

Replicate elements along with their events using jQuery

Every time I utilize ajax to dynamically generate new content using methods like .clone(), append(), etc., the newly created element loses all triggers and events that were programmed =( Once a copy is made, basic functionalities that work perfectly on ot ...

JavaScript onclick event on an image element

I have a JavaScript function that shows images using CSS styles. <script type="text/javascript"> $(function () { $("div[style]").click(function() { $("#full-wrap-new").css("background-image", $(this).css("background-image")); }); }); ...

Struggling to get my chart to render dynamically in vue-chartjs

In my MainChart.vue file, I defined my chart like this: import { Line, mixins } from 'vue-chartjs' const { reactiveProp } = mixins // const brandPrimary = '#20a8d8' export default { extends: Line, mixins: [reactiveProp], props: [& ...

Clickable Parent URL in Bootstrap 5 Dropdown

I'm currently working on creating a Bootstrap 5 Navabar with a dropdown that appears on hover and allows the parent item to be clickable on screens larger than 992px. Successfully implementing the show on hover feature with the following JavaScript: ...

Is it possible to execute MongoDB queries from an AS3 client?

Can native Javascript functions for the mongo shell be run on server side from an AS3 client AIR app? I have experience running Javascript methods embedded/loaded in HTML where SWF is also embedded, and I'm curious if it's possible to make a ser ...

Using React router to handle multiple hierarchical parameters

Having a documentation component in my app, I want the URLs to appear as follows: url: myapp.com/docs url: myapp.com/docs/document-1 url: myapp.com/docs/category-1/document-2 url; myapp.com/docs/category-1/category-2/document-2 The challenge lies in set ...

How can I configure my React Project to direct users to example.com/login.html when they land on the root URL?

My goal is to verify a user's identity through a third-party authentication server. The redirect_uri indicates that after the user logs in, they will be redirected to example.com/login.html. Inside the login.html file, there will be specific html/scr ...