Retrieve data from one array using information from another array. Alternatively, merging the arrays could also be a solution

Welcome, developers, hackers, and watchers!

I'm facing an issue that I can't quite wrap my head around, specifically the part where I need to extract data from one array based on another.

Would merging them help?

Let's take a look at the two arrays:

var teams = ["red", "red", "red", "red", "blue", "blue"];
var scores = [4, 45, 21, 34, 76, 56];

var scoreRed = [];
var scoreBlue = [];

var i;
var scoreBlueIndex;
for (i = 0; i < teams.length; i++){
  scoreBlueIndex = teams.indexOf("blue");
  scoreBlue = scores[scoreBlueIndex];
}

var ii;
var scoreRedIndex;
for (ii = 0; ii < teams.length; ii++){
  scoreRedIndex = teams.indexOf("red");
  scoreRed = scores[scoreRedIndex];
}


console.log(scoreRed);
console.log(scoreBlue);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>

Answer №1

By utilizing an object literal and Array.reduce method, you can achieve something like this ->

var teams = ["red", "red", "red", "red", "blue", "blue"];
var scores = [4, 45, 21, 34, 76, 56];

var results = teams.reduce((a,c,i) => {
  return (a[c] = (a[c] || 0) + scores[i]) && a;
}, {});

console.log(`Red: ${results.red}`);
console.log(`Blue: ${results.blue}`);

return (a[c] = (a[c] || 0) + scores[i]) && a;

The code above may appear complicated at first, but it becomes easier to understand with practice. Initially, the variables passed to this a,c,i represent the accumulator, currentValue, and currentIndex in the reduce function. For more information on reduce, visit -> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce?v=a

a[c] =, This is where we define the object literal, where c can be either blue or red, resulting in a["red"] = or a["blue"] =

a[c] || 0 accounts for the case where the object literal doesn't exist yet, setting the value to 0.

Lastly, we add the current score using i as the index value of the array, accessing the score. score[i].

The && a at the end -> When using reduce, the typical return value is the accumulator, thus (formula) && a ensures it always returns a. This serves as a shortcut to avoid an additional return a line.

Answer №2

Incorrectly, the variables scoreRed and scoreBlue have been declared as arrays when they are meant to be scalar variables. Look at the corrected code snippet below:

var teams = ["red", "red", "red", "red", "blue", "blue"];
var scores = [4, 45, 21, 34, 76, 56];

var scoreRed=0;
var scoreBlue=0;

var i;
var scoreBlueIndex;
for (i = 0; i < teams.length; i++){
  scoreBlueIndex = teams.indexOf("blue", i);
  if(scoreBlueIndex > -1) {
    scoreBlue = scoreBlue + scores[scoreBlueIndex];
    i=scoreBlueIndex;
   }
   else break;
}

var ii;
var scoreRedIndex;
for (ii = 0; ii < teams.length; ii++){
  scoreRedIndex = teams.indexOf("red", ii);
  if(scoreRedIndex > -1) {
     scoreRed = scoreRed + scores[scoreRedIndex];
     ii=scoreRedIndex;
  }
  else break;
}


console.log(scoreRed);
console.log(scoreBlue);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>

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

Adjust the field of view of the camera in ThreeJS

I'm currently working on adjusting the field of vision for a camera without having to create a new one. So far, I've successfully achieved this for the position using the following code: camera.position.set() Now, I'd like to implement a s ...

What is the method for copying table data, including input text as cells, to the clipboard without using jQuery?

I have a basic table that looks like this: <table> <thead> <tr> <th>Savings</th> </tr> </thead> <tbody> <tr> <td>Savings <button type="button" (click)=" ...

The checkbox is not updating as anticipated

I'm currently developing a basic widget that allows the user to change the value of either the check box OR the entire div by selecting them. Below is the code I have implemented: $(document).ready(function() { $(document).on("click", ".inputChec ...

Is it possible to modify the value of just one element within a Nested JSON in Kotlin?

Let's assume we have a JSON as shown below... {"cars": [ { "id": 1, "brand": "Honda", "milesDriven": "100,000"}, { "id": 2, "brand": "Toyota", "milesDriven ...

Could Ramda assist in enhancing pipeline/composition processes with a logging feature?

Considering implementing logging within a composed chain of functions, the following code demonstrates how it can be achieved: const f = R.compose( transformation2, doAlso(x => console.log(`id: ${x.id}`)), transformation1 ) This approach would c ...

Having trouble debugging the current TypeScript file in VS Code because the corresponding JavaScript file is missing

In my current project using Visual Studio Code version 1.17, I am focusing on debugging the current typescript file. As part of my setup, I have a build task in place which generates a corresponding javascript file structure like so: src/folder1/folder2/m ...

How can one utilize a second drop-down list in asp.net to alter the selected index and visibility of a drop-down list?

I am working on an asp.net application that includes a drop down list with the following structure: <asp:DropDownList runat="server" ID="ddlChanges" CssClass="selectstyle" onchange="javascript:ddlChangesChanged();"> <asp:ListItem Text="-- Select ...

Console Error: Attempting to set the 'className' property of null object results in an

I'm experiencing difficulties setting up the code. The function should display all songs by a specific artist when their name is entered and the button is pressed. JavaScript file: /** * Utilizes AJAX to request data about artists from an online sou ...

Display a set of JSON objects on separate lines rather than consolidating them on a single line

When I load a json file and attempt to extract certain values, the output is displayed all on one line. Here is an example of the current output: {"time":"1:2:2","post":"1","user":"4","text":"Masaru Emoto"}{"time":"1:3:8","post":"8","user":"5","text":"Me ...

My redirect is being disrupted by passing a text string with new lines through GET requests

My issue involves submitting a form that utilizes JavaScript to pass a value through GET. Upon reaching the submission page, the function runs successfully, but when redirecting via the header, it ends up on a blank page. The header code for redirection lo ...

Difficulty in understanding sentences in the C language

As I work on enhancing my C programming skills, I have come across a perplexing topic concerning pointer declarations. Specifically, I am keen on understanding the distinctions between these two statements: 1. int *ptr[3]; 2. int (*ptr)[3]; Despite thei ...

Typescript Angular2 filtering tutorial

In Angular 2 using TypeScript, the goal is to search for matching values from an array within an object array. The intention is to filter out any objects where the 'extraService' property contains any of the values from the 'array_values&apo ...

Include an external JavaScript file within a component to display pictures in a web browser using Angular 2

I am developing a website using Angular 2 and need to incorporate a JavaScript file into a component. The goal is for this script to adjust the height of certain images to match the height of the browser window. What is the best way to integrate this scri ...

The Laravel function is not returning as expected on the server

I'm facing an issue with my Laravel project. When the validator fails, the return back function works fine on localhost but on the server it redirects to the root URL. Can anyone help me resolve this problem? Here is my controller code: public functi ...

Disabling the search function when it is clicked (before any actions are taken)

I've recently implemented a search form on my website, where the search field opens up upon clicking the search icon.https://i.stack.imgur.com/UeErx.png To make the search icon clickable, I disabled the search function. var $searchBtn = $search.find ...

I am noticing that my popover is causing my page to shift when I click it. It is expanding the width of my page more than I would

Upon clicking the user id popover on my page, it expands the page width instead of adjusting within the page boundaries. This is the issue: https://i.stack.imgur.com/EqaMo.png There's a small white space present that I want to eliminate. When the po ...

PHP - JSON does not create any output

I have developed a code that displays all the appointments I have for the day. The calendar layout is already set up. However, when I try to run the program using Python, it doesn't function as intended. Here is my code: <?php mysql_connect(dele ...

Add new data to an existing array in Angular 7 without overwriting it

After clicking a button, I'm retrieving data from the WordPress API: <a (click)="initGetComments()">Get comments</a> This is the code snippet: export class AppComponent { commentsResults: CommentsItem[] = []; ...

Is it possible to implement PortalVue in multiple Vue.js single file components?

While working on Vue.js (single file components), I have discovered three methods of passing data around: local state/props, store, and utilizing PortalVue. Through my experiments with PortalVue, I successfully implemented both portal and portal-target wit ...

Sharing information between controllers while being initiated using $rootScope.$emit

I've created a common module that includes a controller, component, and template to initialize the app and set up the base layout. Within this module, there is also a stateful component that makes an HTTP GET request during initialization to fetch a b ...