The art of adding numerous identical elements to a TypeScript array

Is there a way to efficiently add multiple elements with the same value to an array of objects in JavaScript? I know about '.push()' method, but is there a method that can do this with a count specified?

person {
firstName: string;
lastName: string;
age: number;
}

people: Person[];
numberPeople: number;

// example calculation to generate numberPeople: 23

person.push( {firstName: '', lastName: 'Smith', age: 0}, NumberPeople)

I am aware of using a loop structure (for (i=0; i<NumberPeople;i++) person.push), however, it seems cumbersome. Is there a simpler way for achieving this task? I'm relatively new to JavaScript and TypeScript.

I have experimented with .fill() method, but it doesn't allow me to specify values.

Thank you,

I understand that creating a custom function (mpush(obj, count)) is an option, but I prefer a more elegant and standard solution if possible.

Answer №1

If you need to add multiple elements of objects to an array with the same values, there are various methods you can use.

Method 1: Use Array.fill

Note: This method will assign the exact same object to each index of the array from 0 to the length of the array. Learn more here.

type Person = { firstName: string; lastName: string; age: number; };

const numberOfPeople: number = 3;
const defaultPerson = { firstName: '', lastName: 'Smith', age: 0 };

// Fill all elements in the array with the same object
const people = Array(numberOfPeople).fill(defaultPerson);

// You can then change one element by assigning a new object
people[1] = { firstName: 'unique', lastName: 'unique', age: 0 };

This approach helps save memory when default values are consistent, and only new objects are needed for unique individuals.

Method 2: Use Spread Operator and Array.map

If you have an array of different objects but with the same initial values, consider using map.

type Person = { firstName: string; lastName: string; age: number; }

const numberOfPeople: number = 3;

const defaultPerson: Person = { firstName: '', lastName: 'Smith', age: 0 };

const people: Person[] = [...Array(numberOfPeople)]
    .map(_ => ({ ...defaultPerson })); // Creates a shallow copy of the object

Method 3: Use Array.from

type Person = { firstName: string; lastName: string; age: number; }

const numberOfPeople: number = 3;

const defaultPerson: Person = { firstName: '', lastName: 'Smith', age: 0 };

const people: Person[] =  Array.from(Array(numberOfPeople), _=>({...defaultPerson}));

Method 4: Use for...of

type Person = { firstName: string; lastName: string; age: number; }

const numberOfPeople: number = 3;

const defaultPerson: Person = { firstName: '', lastName: 'Smith', age: 0 };

const people: Person[] = [];

for (const _ of Array(numberOfPeople))  people.push({...defaultPerson})

Answer №2

If you need to quickly fill an array with a certain value, the built-in fill() method can come in handy. Simply create an Array object of the desired size and populate it with the value you want repeated.

interface individual {
  name: string;
  profession: string;
  age: number;
}

const sampleIndividual = {name: '', profession: 'Engineer', age: 0}

const persons = Array(numOfPersons).fill(sampleIndividual)

Answer №3

If you want to populate an array with the same object, you can utilize the .fill() method like this:

const NumberPeople = 3;
const people = Array(NumberPeople).fill({firstName: '', lastName: 'Smith', age: 0});

console.log(people);

// With .fill(), the same person is replicated in all positions
console.log(people[2].age); // outputs 0
people[1].age = 4;
console.log(people[2].age); // now outputs 4

//
//
// If having all values pointing to the same object is undesirable, use .map instead:

const people2 = [...Array(NumberPeople)].map(_ => ({firstName: '', lastName: 'Smith', age: 0}));

console.log(people2);
console.log(people2[2].age); // will display 0
people2[1].age = 4;
console.log(people2[2].age); // still displays 0

Answer №4

Insight : In this context, person is treated as an object and the push method will operate on an array. Therefore, it is advisable to use people.push() instead of person.push().

Here are the steps you can take to meet this criteria.

  • Initialize an array based on the value of numberPeople

const numberPeople = 5;

const arr = Array(numberPeople);

console.log(arr); // [undefined, undefined, undefined, undefined, undefined]

  • Next, iterate through this array using Array.map() and populate it with objects.

const numberPeople = 5;

const arr = Array(numberPeople);

let people = [{
    firstName: 'Alpha',
    lastName: 'Beta',
    age: 10
}]

people.push([...arr].map(item => ({firstName: '', lastName: 'Smith', age: 0})));

console.log(people);

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

Storing an array of objects in Firestore using JavaScript presents a challenge

I am attempting to save an object to Firestore which includes an array: { returnMode: false, id: "SE-74c5219a-acfe-4185-9e33-f78b10ac3f1e", prices: [ { price: { twoHours: 0, firstHour: 0, id: "zero&quo ...

An error was encountered with Jquery/Ajax when trying to serialize $(var) due to a syntax error: Unrecognized expression for the

Hello everyone. I'm currently tackling a challenge in my ASP.NET Web API project, as I encountered an error in the following code snippet: function LoadGraph(text) { console.log(typeof(text)); $.ajax({ url: "/api/Graph/LoadGraph", ty ...

Manipulating HTML content with Javascript Array

Is there a way to retain Javascript context from an array? Any suggestions for improving this code? SAMPLE: <html> <script type="text/javascript"> var rand = Math.floor(Math.random() * 6) + 1; var i = Math.floor(Math.random() * 6) + 1; var ...

Node.js: Exploring the Differences Between Synchronous and Asynchronous Code

Currently, my team is delving into the world of node for an internal project and to gain a deeper understanding of how to utilize this technology effectively. As individuals without a specific asynchronous background, we are facing some challenges with th ...

Authorization based on user roles in Node.js or Express.js

Are there any modules available for implementing role-based authorization in node.js or Express js? For example, having roles such as Super Admin, Admin, Editor, and User? ...

Evaluating function declaration - comparing interface to type alias

Here is a function that I need to create a validator for: function (n: number) { return {s: n}; } I have come across two options for creating the validator: Option 1: Interface interface ValidatorFnInterface { (n: number): { [key: strin ...

Adjusting the dimensions of the central container

Does anyone have suggestions on how to resize the middle red container when the window is resized, considering the fixed-width black containers on the left and right? I am aware that this can be achieved using jQuery by calculating the window width and a ...

Ways to implement a custom scrollbar across an entire webpage:

I am trying to implement the Jquery custom content scroller on my webpage to replace the default scrollbar. However, I am facing difficulties in getting it to work properly. You can view my code on Codepen. Although the plugin works fine with smaller blo ...

Is it possible for a JWT generated using RS256 to be decoded on the jwt.io platform?

After setting up my first Express server and implementing user authentication with jwt, I'm now searching for a method to encrypt the jwt in order to prevent users from viewing the payload on the website. I am curious if anyone is aware of an encryp ...

Tips for displaying a bot counter in a Discord.js guild

Thinking of creating a bot counter in discord.js. Imagine this scenario: If I type: "!bots", the bot will respond with something like: "There are 11 bots on this server" I attempted to use the following code, but it only gives me the ...

Navigating through the conditional "where" clause in IndexDB for various browsers

I have successfully implemented indexdb because it provides support for all browsers. I have managed to add and retrieve data from indexdb, but now I want to implement a where clause condition. For example, I have fields like Product Name, Pathogen, Diseas ...

Looking for the location to input the stats argument in the analyze API from Diffbot

Utilizing the Diffbot analyze API to identify page types and hoping for results similar to this: {"stats":{"times": {"docParseTime":0,"docGlobalsTime":0,"fetchAndRenderTime":586,"typeTime":0},"fromCache":true,"types":{"recipe":0,"discussion":0,"audio":0," ...

Exploring the concept of returning objects in jQuery

I'm really trying to grasp the inner workings of how jQuery creates the return object when searching for DOM elements. I've delved into the source code, but I must admit that it's not entirely clear to me yet. So, I'm reaching out here ...

The ellipsis menu pops up next to the final video in the series of HTML videos

Currently, I am working on rendering HTML video tags for playing videos. However, I am facing an issue where the three dots menu is not appearing near the button that triggered it, instead, it displays near the last video's three dots. To illustrate t ...

Reactjs Promise left hanging in limbo

How can I resolve the pending status of my promise? I have a modal with a form submit in it, where I am trying to retrieve the base64 string of a CSV file. While my code seems to be returning the desired result, it remains stuck in a pending state. c ...

What distinguishes defining an interface externally versus internally within a class?

In my interpretation, here is how you can declare an interface within a class: class A { a: number constructor() { this.a = 0 } } And this is the method to define an interface outside of a class: interface A { a: number } class A { construct ...

Utilizing ExpressJS to save uploaded files using the FileReader object from the front-end

Despite researching multiple posts on this topic, I am still unable to successfully upload a file after numerous adjustments. My React form includes a PDF file upload component which looks like this: <Input onChange={(e) => this.handleFileUpload(e) ...

Encountering an undefined property error while using Array.filter in Angular 2

hello everyone, I am currently faced with an issue while working on a project that involves filtering JSON data. When using the developer tools in Chrome, it keeps showing me an error related to undefined property. chart: JsonChart[] = []; charts: JsonC ...

errorMessage": "Issue: Type Error - Unable to iterate over (intermediate value)

Currently, my setup involves using mysql2 to establish a connection with AWS Aurora DB. Unfortunately, I am encountering issues with connecting to the cluster and retrieving records. connection = createConnection({ host: 'music-instance-2 ...

What is the best way to arrange an array of objects in JavaScript by numerical order and then alphabetically?

Possible Duplicate: Sorting objects in an array by a field value in JavaScript I'm looking to sort an array of objects both numerically (by id) and alphabetically (by name). However, the current method I'm using is not giving me the desired ...