Obtain the position of a value within an array that has been grouped together

In my JavaScript code, I am dealing with two arrays. One array contains Ids:

[1,1,1,2,2,2,3,3,...]

The other array holds values:

[0,1,0,0,0,1,1,0,...]

What I need to do is determine the zero-based index of the group of Ids where the corresponding value is 1.

For example, for these arrays, the result could be:

[1,2,0,...]

This means that it is the index of the 1 in the Values array when grouped by the unique values in the Id array.

Keep in mind that there should only be a single 1 per group of Ids, even if the groups are not in sequential order like:

[1,1,2,1,2,2,3,3,...]. In this case, I still want the correct index for the grouped Ids.

I initially tried using a while loop but encountered duplicate values. Then I attempted to filter my array without complete success. Is there a way to achieve this task in JavaScript?

Examples:

Array 1 (IDs): [1,1,1,2,2,2,3,3,3,3]  
Array 2 (Values): [0,1,0,0,1,0,0,0,0,1]  
Result Array: [1,1,3]

Array 3 (IDs): [1,2,1,3,1,1,2,2,3]  
Array 4 (Values): [0,0,1,0,0,0,1,0,1]   
Result Array: [1,1,1]

Answer №1

If you assign an index counter to the same group, you can retrieve the value when a value of one is encountered.

Example 3:

[1, 2, 1, 3, 1, 1, 2, 2, 3]  ids
[0, 0, 1, 0, 0, 0, 1, 0, 1]  values
 0  0  1  0  2  3  1  2  1   indices by group
       ^           ^     ^   result

function getIndices(ids, values) {
    var map = new Map;
    return ids.reduce((r, v, i) => {
        if (values[i] === 1) r.push(map.get(v) || 0);
        map.set(v, (map.get(v) || 0) + 1);
        return r;
    }, []);
}

// [1, 2, 0]
console.log(...getIndices([1, 1, 1, 2, 2, 2, 3, 3], [0, 1, 0, 0, 0, 1, 1, 0]));

// [1, 1, 3]
console.log(...getIndices([1, 1, 1, 2, 2, 2, 3, 3, 3, 3], [0, 1, 0, 0, 1, 0, 0, 0, 0, 1]));

// [1, 1, 1]
console.log(...getIndices([1, 2, 1, 3, 1, 1, 2, 2, 3], [0, 0, 1, 0, 0, 0, 1, 0, 1]));

Instead of using a Map, you have the option to utilize an object as a hash table for indexing the values.

function getIndices(ids, values) {
    var hash = Object.create(null);
    return ids.reduce((r, v, i) => {
        hash[v] = hash[v] || 0;
        if (values[i] === 1) r.push(hash[v]);
        hash[v]++;
        return r;
    }, []);
}

// [1, 2, 0]
console.log(...getIndices([1, 1, 1, 2, 2, 2, 3, 3], [0, 1, 0, 0, 0, 1, 1, 0]));

// [1, 1, 3]
console.log(...getIndices([1, 1, 1, 2, 2, 2, 3, 3, 3, 3], [0, 1, 0, 0, 1, 0, 0, 0, 0, 1]));

// [1, 1, 1]
console.log(...getIndices([1, 2, 1, 3, 1, 1, 2, 2, 3], [0, 0, 1, 0, 0, 0, 1, 0, 1]));

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 existing session persists when a new user logs in, instead of being destroyed

Security measures will be implemented at a later time Currently, I have a login script that operates in two scenarios. It either returns a message in JSON format, indicating issues such as incorrect login credentials or empty fields, or it initiates a ses ...

Implement a function in Java called "ReturnMethod" that takes in an integer array as input and outputs a new array that is both ordered and

Consider the following integer array: int[] arr = {1, 2, 5, 8, 9, 10, 20, 80, 9, 0, 100, 90, 30, 55, 22, 87, 88, 22, 33, 22, 1, 2, 3}; Requirement: The task at hand is to write a method that takes an integer array as input, sorts it in ascending order, an ...

What is the best way to execute a sequence of consecutive actions in a protractor test?

To achieve logging in, verifying, and logging out with multiple users, I decided to use a loop. I came across a helpful post that suggested forcing synchronous execution. You can find it here. Below are the scripts I implemented: it('instructor se ...

Getting a value from a JavaScript variable and implementing it on a webpage (post) - A step-by-step guide

I am currently utilizing a third-party service that offers the ability to input custom HTML in order to gather information through a form. There is a form page where users input their details, and then there is a post form page. I reached out to the servic ...

Why is it that my Vue application's environment variables are easily visible in Google Chrome Inspector, instead of being hidden or encrypted?

Hey there everyone, I recently completed building a Vue application, and everything seems to be functioning as expected when I run npm run build. However, upon inspecting the app using Google Chrome developer tools, I came across an interesting observatio ...

Regular expressions can be used to target a specific sentence that contains multiple words

With this regular expression, I am able to choose a sentence based on a single word: [^.]* word [^.]*\. Is there a way to select a sentence with two or more words conditionally? For instance, how would I go about selecting a sentence if word A and ...

Encountering an unanticipated reference error while attempting to paste the data

// Modify the layout function document.addEventListener('DOMContentLoaded', function() { function modifyLayout(productId) { // Referencing the original card and detailed card const originalCard = document.querySelector(&ap ...

Generate a fresh row for a table using JQuery and insert a button with a unique identifier into the cell

Can someone help me with dynamically creating and deleting table rows using jQuery? The add row functionality is working fine, but the delete row function isn't because the onclick event is not being attached to the dynamically created button. Any sug ...

The function is failing to return a false value

I have encountered a problem with my code - it works fine in Chrome but not in IE or Firefox. I've tried using return false; and event.preventDefault() but they don't seem to be effective in Firefox. The issue arises when the button grabs informa ...

Auto Start Feature for jQuery Slider Function

Hey there, I currently have an image slider on my website that allows users to navigate through images by clicking on preview and next buttons. My query is: would it be possible to implement an auto start feature instead of having to click manually? Belo ...

Ways to transmit data from PHP to JavaScript

I have a file called "hotlaps.php" where I've created a JavaScript script: echo "<body onload=\"myFunction(".$array_1.",".$array_2.",".$array_3.");\">"; In my "hotlaps.js" file, I have the following function: function myFunction(arr ...

The NextJs image entered into an endless loop, throwing an error message that said: "The 'url' parameter is correct, but the response from the

I have been using next/image component with next js version ^12.2.3-canary.17 for my current project. The issue I am encountering is that some images are missing from the source directory, resulting in infinite error logs like the one shown below: https:/ ...

Currently, I am utilizing v-model to bind one input and name for the other. My main focus is on exploring the various methods for retrieving and manipulating their

I created a form with various input fields and upon submission, I am displaying the data in a modal. Although it functions correctly, I have concerns regarding the cleanliness of my code. Below is the simplified HTML structure: <div id="app"> < ...

What is the reason behind the variation in how the index is implemented with the inequality sign based on its direction? (MySQL index)

CREATE TABLE test_table ( id bigint(20) NOT NULL AUTO_INCREMENT, PRIMARY KEY (id) ); After creating the table in this manner, whether or not the index is used depends on whether the direction of the inequality sign references a number or a field. This ...

Using Session Value to Automatically Select Drop Down Box

<select> <?php foreach($result as $city) { ?> <option value="<?php echo $city->city_name; ?>" <?php if( strtolower($this->session->city) == strtolower($city->city_name) ) { echo "selected"; } ?> ...

Display a button only when the root/parent element is being scrolled up or down, and hide the button if the

Is there a way to dynamically display a button based on whether the root or parent element needs to be scrolled? The button should be hidden if scrolling is not needed. Consider this scenario: If an element is set with a max-height of 200px and overflow ...

There was an issue with the specified entry-point "auth0/angular-jwt" as it is missing required dependencies

I am currently working on an Angular project with the following versions: @angular-devkit/architect 0.901.1 @angular-devkit/core 9.1.1 @angular-devkit/schematics 9.1.1 @schematics/angular 9.1.1 @schematics/update 0.901.1 rx ...

Elements overlapped with varying opacities and responsive to mouse hovering

In this Q/A session, we will explore a JS solution for managing the opacity of overlapping elements consistently during hover. Objective Our goal is to create two transparent and overlapping elements, similar to the red boxes showcased below. These eleme ...

What is the best way to access the front camera on both Android and iOS devices in order to capture a photo using Vue.J

I am currently developing a PWA Vue.Js application and I am trying to implement a feature that allows users to take a picture with the front camera on their mobile devices. Although I have managed to write code that works on my desktop browser, I have bee ...

The Prototype of a Variable: Its Intrinsic Value

I have a basic prototype and I am looking to continuously update the 'Balance' value as payments are made. Can anyone advise me on how to maintain the 'Balance' variable using HTML, CSS, Javascript, and Bootstrap? After clicking Submit, ...