Two arrays with varying sizes, utilizing one array repeatedly within a loop once its maximum index is reached

I have two arrays set up, and my goal is to iterate through the larger array and assign a property to it using randomly selected IDs from the smaller array.

//The actual length of the users array is 140
const users = [
  {
    name: "John Roberts",
    uid: "49ikds_dm3idmssmmi9sz"
  },
  {
    name: "Peter Jones",
    uid: "fmi33_sm39imsz9z9nb"
  }
]

//The actual length of the cars array is 424
const cars = [
  {
    manufacturer: "BMW",
    model: "320d",
    year: "2010",
    user: null
  },
  {
    manufacturer: "BMW",
    model: "530d",
    year: "2018",
    user: null
  },
  {
    manufacturer: "AUDI",
    model: "RS6",
    year: "2014",
    user: null
  }
]

for(let i = 0; i < cars.length; i++){
  //In this example, if the index is 2 or higher, users[2] will be undefined
  cars[i].user = users[i].uid;
}

Essentially, I am looking for a way to efficiently utilize the small users array. Once the variable i reaches 2 or more in the example above, then accessing users[2] will return undefined.

Does anyone have a clever solution to suggest that could help me overcome this challenge?

Answer №1

Utilize the % operator to ensure accurate indexing and reusing of users.

const users = [
  {
    name: 'John Roberts',
    uid: '49ikds_dm3idmssmmi9sz',
  },
  {
    name: 'Peter Jones',
    uid: 'fmi33_sm39imsz9z9nb',
  }
];

const cars = [
  {
    manufacturer: 'BMW',
    model: '320d',
    year: '2010',
    user: null,
  },
  {
    manufacturer: 'BMW',
    model: '530d',
    year: '2018',
    user: null,
  },
  {
    manufacturer: 'AUDI',
    model: 'RS6',
    year: '2014',
    user: null,
  },
];

for (let i = 0; i < cars.length; i += 1){
  cars[i].user = users[i % users.length].uid;
}

console.log(cars);


A jaw-dropping ES6 solution! (must see)

const users = [
  {
    name: 'John Roberts',
    uid: '49ikds_dm3idmssmmi9sz',
  },
  {
    name: 'Peter Jones',
    uid: 'fmi33_sm39imsz9z9nb',
  }
];

const cars = [
  {
    manufacturer: 'BMW',
    model: '320d',
    year: '2010',
    user: null,
  },
  {
    manufacturer: 'BMW',
    model: '530d',
    year: '2018',
    user: null,
  },
  {
    manufacturer: 'AUDI',
    model: 'RS6',
    year: '2014',
    user: null,
  },
];

const result = cars.map((car, index) => ({
  ...car,
  
  user: users[index % users.length].uid,
}));

console.log(result);

Answer №2

To properly handle the user[i] variable, you can check for its existence and assign a default value:

for(let i = 0; i < cars.length; i++){
  //if index is 2 or greater in this example. users[2] will be undefined
  cars[i].user = users[i] && users[i].uid || /*Default value:*/ null;
}

An alternative approach is using an if statement:

for(let i = 0; i < cars.length; i++){
  //if index is 2 or greater in this example. users[2] will be undefined 
  if (users[i]) {
    cars[i].user = users[i].uid;
  } else {
    cars[i].user = null; // Or another default
  }
}

------------------ Update to take account of comment -----------------

If you want to loop through users and circle back to the beginning of the array when you reach the end, you can utilize modulo %

let user_idx = null
for(let i = 0; i < cars.length; i++){

  user_idx = i % users.length

  //if index is 2 or greater in this example. users[2] will be undefined
  cars[i].user = users[user_idx].uid || null;
}

Answer №3

element, you will find a straightforward solution. All you need to do is implement the following logic:
$.grep(users, function(user, i ) {  cars[i].user = user.uid;});

Answer №4

var persons = [
{
name: "Emily Johnson",
uid: "34ids_fa2iiemasl123v"
},
{
name: "Michael Smith",
uid: "fmi33_sm39imsz9z9nb"
}
]

//Actual length of the array is 424
var vehicles = [
{
make: "Toyota",
model: "Camry",
year: "2015",
owner: null
},
{
make: "Honda",
model: "Civic",
year: "2019",
owner: null
},
{
make: "Ford",
model: "Mustang",
year: "2021",
owner: null
}
]

vehicles.map(function(vehicle){
var randomIndex = Math.floor(Math.random() * Math.floor(persons.length))
vehicle.owner = persons[randomIndex].uid;
})
console.log(vehicles)

Answer №5

choice A:

for(let index = 0; index < vehicles.length; index++){
   vehicles[index].driver = drivers[index % drivers.length].license;
}

choice B:

for(let index = 0; index < vehicles.length; index++){
   vehicles[index].driver = drivers[Math.round(Math.random() * (drivers.length - 1))].license;
}

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

Passing a jQuery dialog variable for use in a php function using ajax

I am struggling to successfully pass variables from jQuery to a PHP function using AJAX. I have included the necessary HTML and script, but I'm confused as to whether the PHP file specified in the "url:" parameter should be external or can it be follo ...

What is the most efficient way to insert values into a multidimensional array?

Hello everyone, I am facing an issue and need some assistance. I am trying to insert values into specific array keys, but I am getting a lot of null values inserted. Here is the format I am aiming for: { "20": { "0":10, "1":20, ...

What are the differences between using embedded documents and references in a mongoose design model?

I am currently in the process of developing a discussion forum using Node.js and mongoose. The structure I have in mind involves users being able to participate in multiple forums, with each forum containing multiple comments. Additionally, users should ha ...

Issue with Webstorm not automatically updating changes made to JavaScript files

On my HTML page, I have included references to several JavaScript files such as: <script type="text/javascript" src="MyClass.js"></script> When debugging in WebStorm using a Python SimpleHTTPServer on Windows with Chrome, I am able to set bre ...

Struggling to grasp the concept of Linked lists in the C language because of a lack of comfort with Pointers? Just take it slow and steady as a beginner

After completing two chapters on 'Pointers' in a book, I find myself in need of more practice with certain sub-topics. These include using pointer notations instead of array notations and working with arrays of pointers to some extent. I have a ...

Initiating the animation/game loop for a three.js object

I am utilizing angularJS and Three.js for the frontend of my project. The Three.js object is created in the following manner: var ThreeObject = (function() { //constructor function ThreeObject() {} ThreeObject.prototype.init = functio init (){ //initial ...

Converting JSON data into a serialized format using Python and Django

I'm facing an issue where I need to serialize the entire data set from the profile page, but the problem is that the output data I receive contains single quotes instead of double quotes, making it difficult to parse later on: View: def profile_page( ...

How can I modify this section of the code in Google Script to retrieve all columns?

My question is, how can I modify this code to fetch all columns from the array instead of just [0,1,2,3] Here is the line of code in question: const new_table = [0,1,2,3].map(x => make_row_from_col(this_table, x)).join('\n'); Using obje ...

Can you explain the distinction between using call and apply?

Can you explain the distinction between utilizing Function.prototype.apply() and Function.prototype.call() to execute a function? const func = function() { alert("Hello world!"); }; func.apply() compared to func.call() Do performance dispar ...

Is it safe to utilize an AngularJS filter for parsing a URL?

When working on a web application, my client-side (angularjs based) receives JSON data from a web service. The JSON can contain a text field with some URLs, such as: blah blah ... http://www.example.com blah blah blah ... To render these links as HTML, I ...

The reversal process hit a snag and ended up yielding the original number

I seem to be struggling with the logic of my loops, can you help me identify my mistake? The task is to reverse the given number. Here is my current code: #include <iostream> #include <string> using namespace std; int main(){ string numbe ...

Phonegap app developer encounters issue with sending ajax requests

Recently, I encountered an issue with Ajax in my Phonegap development. Previously, it worked perfectly but now when I call the Ajax function, nothing happens. Here are the steps I have taken to troubleshoot: 1) I edited the config.xml file and added the f ...

Transformation of an Ajax array into an associative array

Currently, I am working on creating an API using Ruby on Rails and facing a challenge with sending an array through ajax. The task seems straightforward, but the issue arises when the array is received as an associative array instead of a regular one! Es ...

Issues with loading NextJS videos can occur when accessing a page through a link, as the videos may fail to load without

Issue Greetings. The problem arises when attempting to load muse.ai videos on-page, specifically when accessing the page with a video embedded through a NextJS link. To showcase this issue, I have provided a minimal reproducible example on StackBlitz her ...

ReactJS: Checkbox status remains consistent through re-rendering of Component

I have developed a JSfiddle example Initially, this fiddle displays a list of checkboxes based on the passed props to the component. When you click the Re-render button, the same component is rendered with different props. Now, please follow these steps- ...

Avoiding the capturing of events on $( document ).mousemove

Each time the browser detects a $( document ).mousemove event, my function is invoked. The performance is smooth with an empty page, but once I introduce a div element and hover over it, the function gets executed twice: first on the document and then agai ...

The dilemma between installing Electron or installing Electron-Builder: which one

When it comes to installing Electron for an Electron app with React, the method can vary depending on the tutorial. Some tutorials use electron-builder while others do not, but there is little explanation as to why. First: npx create-react-app app cd app ...

GLSL uniform array of variable size

In my quest to incorporate a "fog of war" feature into my strategy game, I delved into various Q&A threads on a popular coding platform. It became clear to me that utilizing custom GLSL shaders was the way to go. I began by defining an array called "vi ...

initiate scanning for HTTP GET calls

My current project involves using electron to create an application that serves multiple image files through a webserver using express. Another app built for Android is responsible for retrieving and posting files to this server. While I have successfully ...

JavaScript Ping Pong Challenge

I'm currently investigating why the browser returns NaN for the Positions. The game is being rendered in a loop and updated as soon as the monitor is ready, which is defined in the update() function and runs infinitely. The reset() function is a part ...