Various designations for varying entities of identical category

I want to update an array of objects with a type 'person' to have unique identifiers like 'person0', 'person1', and so on. Currently, the setup looks like this:

var population = [];
var populationCount = 0;

function person(id, age) {
    //simplified version
    this.id = id;
    this.age = age;
}

function createPerson() {
    population[populationCount] = new person();
    population[populationCount].id = populationCount;
    population[populationCount].age = 0;

    populationCount++;
}

for (var i = 0; i < 10; i++) {
    createPerson();
}

At the moment, the array holds instances as "person, person, person, ..." but my goal is to have it as "person0, person1, person2, ...".

I see the value in doing this because if, for example, population[100] were to die, their place would be taken by population[101], assuming I just use population.splice[100] when they pass away. With that change, population[100] would then have the ID 101, and having distinct 'names' in the array could make locating individuals easier using indexOf.

Answer №1

You have mistaken a type for an identifier.

Every instance that you create represents a person, and that fact remains unchanged. Object types are fixed - person[6] will always be an instance of a person.

The best way to distinguish one instance of person from another is either through the id property or an index.

Your code structure could use some improvement. The person function should ideally be a constructor function with two arguments, but in your implementation, you are setting these as properties instead of passing them during construction. Additionally, the createPerson function should solely focus on creating a person, not adding it to an array.

A better approach to organizing your code would be:

var population = [];
var populationCount = 0;

// Following conventions, constructor functions should be Pascal-Case
function Person(id, age){
    // A simplified version
    this.id = id;
    this.age = age;
}

function createPerson(){
  // Refactor this function to just return a new Person instance,
  // avoiding any coupling with how it will be used.
  
  // Also, ensure to pass the necessary arguments during creation
  return new Person(++populationCount, 0);
}

for(var i = 0; i < 10; i++){
  // Add the created Person to the array after deciding on its usage
  population[populationCount] = createPerson();
}

console.log("The population includes: ", population);
console.log("The last person in the population is: ", population[population.length - 1]);
console.log("The third person in the population belongs to: ", population[2].constructor.name);
console.log("The third person in the population has an id of: " + population[2].id);

If you are worried about mismatching indexes with ids, you can implement a "reset" functionality like so:

var population = [];
var populationCount = 0;

function Person(id, age){
  this.id = id;
  this.age = age;
}

function createPerson(){
  return new Person(++populationCount, 0);
}

for(var i = 0; i < 10; i++){
  population[populationCount] = createPerson();
}

// Remove the first 5 people:
population.splice(0, 5);
console.log("First 5 individuals have been removed. Array now contains: " + population.length + " people.");
console.log("The id of the first person is: " + population[0].id);


// **************************************************************************
// Generate a new array with old members but updated ids
var newPopulation = [];
function rePopulate(array){
  newPopulation = array.map(function(element){
    element.id = newPopulation.length + 1;
    return element;
  });
}
rePopulate(population);

console.log("The array has been recreated with adjusted ids");
console.log("The id of the first person is now: " + newPopulation[0].id);

If you wish to locate a specific Person in the array based on their id without knowing the index, you can use a simple "find" function:

var population = [];
var populationCount = 0;

function Person(id, age){
  this.id = id;
  this.age = age;
}

function createPerson(){
  return new Person(++populationCount, 0);
}

for(var i = 0; i < 10; i++){
  population[populationCount] = createPerson();
}

// Eliminate the first 5 people:
population.splice(0, 5);
console.log("First 5 individuals have been eliminated. Array now contains: " + population.length + " people (with id's 6 - 10).");
console.log("The id of the first person is: " + population[0].id);


// ***********************************************************************
// Use a simple "find" operation to locate a person based on their id 
// without needing to know the index at all
function findPerson(id) {  
  return population.find(function(person){
     return person.id === id;
  });
}

var desiredId = 7; // Specific id to search for
console.log("The individual with id 7 is: ",  findPerson(desiredId));

Answer №2

When you express your desire to include person0, person1, person2, and so on, you are essentially asking for an infinite variety of unique types, not just individual objects. Unfortunately, creating these types dynamically is not something I am familiar with. As suggested in the comments, using key-value pairs might be a viable solution. It seems like you are already giving each person a distinct identifier.

One approach could be to nest these objects within an overarching object, for example:

var persons = [
    { 
        person0:
        {
            id: 0,
            age: 69,
            name: 'john doe'
        },
        person1:
        {
        ...
        },
        ...
    }   
] 

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

The module '@algolia/cache-common' is missing and cannot be located

summary: code works locally but not in lambda. My AWS lambda function runs perfectly when tested locally, utilizing Algolia within a service in the server. Despite installing @algolia/cache-common, any call to the lambda results in a crash due to the erro ...

JavaScript is reliant on the presence of the alert() function to properly function

I have a JavaScript function that performs well, except for when I remove or comment out the alert() line. This function is designed to calculate the sum of values in up to 30 fields if they are present and contain a value. Here is an example of the HTML ...

Fade out a dynamically loaded content block using jQuery

I am currently developing a small app and encountering issues with deleting (fading out) dynamically loaded div elements using jQuery. The problem occurs when adding a new content box. If the page is reloaded and the content box is rendered normally (from ...

JavaScript - Dynamically Disable Select Option Elements Depending on the Selected Option

I'm currently working on a form that includes two select elements. Each of these select elements contains multiple options with corresponding values. The first select element, identified by the id "average," has five options while the second one, iden ...

Using Three.js BVHLoader in React/React Native applications

I am currently working on developing an application or website for displaying BVH animation. I came across a BVHLoader example in Three.js that I found interesting: BVHLoader example. I am aware that React and React Native can be used with Three.js as we ...

What is the most efficient way to combine several properties of the same element within an array?

I am working with an array containing personal information such as names and ages. My goal is to create a new property for each element in the array by combining certain properties together. Here is the initial array: var list = [{name: "James", ...

The zoom level on Google Maps adjusts based on the size of the window when it

In reference to my previous inquiry about Google maps responsive resize, I am now looking to incorporate dynamic zoom levels based on the window size. Specifically, I want the map to automatically adjust its zoom level when the browser window is resized -- ...

Sending data to a React component from regular HTML

I have a question about implementing a method to pass custom attributes from HTML elements as props to React components. Here's an example: function someFunction(props) { return <h1>props.something</h1> } HTML: <div id="someEl ...

What is the best method to compare dates in JavaScript/JQuery to determine if one comes before the other?

I am completely new to JavaScript development and I need to accomplish the task below: I have 2 input tags containing 2 strings representing dates in the format 01/12/2014 (DAY/MONTH/YEAR). These input tags are used to search for objects with a date field ...

Managing CSS classes in Vue js - Best practices

My challenge is to dynamically add and remove classes in response to input validation using the textfield component from Google Material. If the text input fails validation, I need to display a red border around the input field along with a warning message ...

Is it possible to conceal my Sticky Div in MUI5 once I've scrolled to the bottom of the parent div?

Sample link to see the demonstration: https://stackblitz.com/edit/react-5xt9r5?file=demo.tsx I am looking for a way to conceal a fixed div once I reach the bottom of its parent container while scrolling down. Below is a snippet illustrating how I struct ...

Retrieve the value of a property in a directive's isolated scope

Is there a way to access the isolated scope's property in the directive tag? Let's take a look at a simplified example: angular.module('app', []) .controller('myController', function() { var result_el = document ...

Transform unidentified individuals into authenticated users using Firebase Authentication for Google

Currently, I am integrating Firebase Auth with VueJS and facing the challenge of converting an anonymous authentication user to a registered user using Google. I have implemented the following code snippet from a reference: fromAnonymousToGoogle: funct ...

Can you explain the relationship between HTML 5 Canvas coordinates and browser pixels?

When trying to use HTML 5 canvas as a drawing board in my application, I encountered an issue. The drawings appear at an offset from the mouse pointer. My method involves using the Jquery .offset function to determine the event's position on the canv ...

Pick and modify a particular component in ReactJS

Currently, I am working on a project in ReactJS where I am attempting to toggle the colors of two buttons. While I have successfully set the active state property of the selected button, I am facing challenges with changing the style of another button (cal ...

Receiving blank information from Firebase

I am struggling with retrieving data from my Firebase tree and converting it into a JSON object. https://i.sstatic.net/YmxRh.png Despite trying the code below, I'm only getting an empty result on my browser: const http = require('http&apos ...

Tips on utilizing imacros for extracting image URLs

I am currently experimenting with the use of imacross for web scraping, but I have encountered a roadblock when it comes to extracting image URLs from markdown code like the one provided below. <div class="dpimages-icons-box"> <a href="http: ...

Animate Scrolling on Your Website with jQuery

I'm having some trouble implementing a page scrolling function on my website using jQuery. It currently works fine, but I want it to only respond to the first scroll event and then block any subsequent events until the animation completes (700ms) befo ...

Angular-in-memory-web-api experiencing multiple collection errors with Error 404

I'm currently utilizing the angular-in-memory-web-api module to simulate server responses. Here is the implementation of in-memory-data.service.ts import { Injectable } from '@angular/core'; import { InMemoryDbService } from 'angular-i ...

Javascript continuously swaps out text from distinct strings in a loop

I wrote a loop to split a string and search for certain text to replace it with another string. Here is an example of what I have done: function replaceStr(str, find, replace) { for (var i = 0; i < find.length; i++) { str = str.replace(new RegE ...