Restrict or diminish an array of strings based on a specific substring

I have an array containing various strings like:

let arr = ["cap:1", "col:red", "cap:3", "cap:1", "col:blue", "screen:yes"]

and I'm looking to create a new array with one item from each category of substrings ("cap", "col", "screen"), choosing the one with the smallest index:
let newArray = ["cap:1","col:red","screen:yes"]

//"cap:1" which is taken from arr[0]

I've attempted solving this problem in the following way:

const newArr = (arr) => {
    let c= []
    let c = [...c, arr[0]]  
    for(let i = 1; i<arr.length; i++){
        for (let j=0; j<c.length; j++){
            if(arr[i].split(":")[0] !== c[j].split(":")){
                c = [...c, arr[i]]
            }
        }
    }
    return c  
}

However, this approach leads to an infinite loop and results in output like:

["cap:1","col:red","col:red","col:red","col:red","col:red","col:red","col:red"...
Could someone please assist me with this issue?
Thank you!

Answer №1

When dealing with nested for loops and iterating through an ever-increasing array, it's easy to land in an infinite loop situation. To avoid this, consider using an object as a reference point instead.

let arr = ["cap:1", "col:red", "cap:3", "cap:1", "col:blue", "screen:yes"];
const newArr = (arr) => {
  let c = [];
  const suffixObj = {};
  for (let i = 0; i < arr.length; i++) {
    const getPrefix = arr[i].split(":")[0];
    if (!suffixObj.hasOwnProperty(getPrefix)) {
      c.push(arr[i]);
      suffixObj[getPrefix] = true
    }
  }

  return c
};

console.log(newArr(arr))

Answer №2

If you use a Set and split the first parts of an array, you can then return an array from the set.

Simply follow this example:

const
    items = ["cap:1", "col:red", "cap:3", "cap:1", "col:blue", "screen:yes"],
    types = [...new Set(items.map(item => item.split(':', 1)[0]))];

console.log(types);

Answer №3

Your logic lacks the ability to confirm whether the prefix of the current element was not located in newArr. Additionally, the condition

arr[i].split(":")[0] !== c[j].split(":") is comparing a string to an array, yielding a result of <code>true
- string !== array.

Perhaps you intended to write

arr[i].split(":")[0] !== c[j].split(":")[0]
, which still would not produce the desired outcome.

You can avoid using the inner loop and instead check each element against newArr by utilizing c.every(el => !...) like this:

let arr = ["cap:1", "col:red", "cap:3", "cap:1", "col:blue", "screen:yes'];

const newArr = (arr) => {
    let c = [arr[0]]; 
    for(let i = 1; i<arr.length; i++) {
        if( c.every(el => !arr[i].startsWith( el.split(':')[0] )) ) {
            c = [ ...c, arr[i] ];
        }
    }
    return c; 
}

console.log( newArr( arr ) );

Answer №4

Using Array.Reduce is a smart approach for consolidating multiple array values into a concise object structure. By breaking down the entries into key-value pairs and selecting the first entry for each key, you can efficiently achieve this transformation. Here's a sample implementation that may suit your needs:

const groupFirstValues = arr => arr.reduce((result, currentValue) => {
   const parts = currentValue.split(':');
   const key = parts[0];
   const value = parts[1];
   if (!result.hasOwnProperty(key)) {
      result[key] = value;
   }
   return result;
});

If you require the output to be in array format, you can reconstruct the data accordingly. However, accessing the resulting object should still offer decent performance.

Answer №5

Check out this helpful tip for you! Start by organizing all the information into a key-value format. Once you have this stream, you can simplify it by only keeping the first occurrence.

let updatedData = data.map(function(item){
        return item.split(":")
    }).reduce(function(accumulator, current){
        if(accumulator[current[0]] === undefined){
            accumulator[current[0]] = current[1]
        }
        return accumulator
    })

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

Tips for transporting an npm module to a different file without reliance on the require function in that specific file

I am curious about how to export the npm module to another file without utilizing the required function in that file. -index.js- const cv = require("opencv4nodejs"); const add = require("./addon"); cv.imshowWait("", add.img( ...

Angular Cascade of Multiple Requests

I am currently working on a project where I need to develop a service that can take CSV data, convert it into rows, and then make API requests for each row, adding the formatted results to an output string. To explain further, my code (written in Coffeesc ...

The bcryptjs function bcrypt.compare consistently gives a result of false

I'm having trouble with the bcryptjs library in my React and Node js project. Despite online verifiers confirming that the password and hash are valid, I can't seem to get it to return true. I've double-checked the length, but it's stil ...

Querying in mongodb based on a field in a referenced document: Tips and techniques

I am working with two collections in MongoDB - Products and Users. Each product document contains a field called ownerId which links to a user in the users collection. Additionally, each user has a Boolean field called isActive. My goal is to retrieve all ...

What could be the reason for the lack of data updates in my component?

I am having an issue with a simple component in my code. Here is the code snippet: <my-comp :item="item"></my-comp> // in script components: { MyComp }, data : { item: 'hello' } After I assign a value to the data item, it on ...

Is it possible to include an onclick event in a hyperlink tag to initiate an ajax call

I am looking to incorporate an ajax call within a hyperlink tag "a". The purpose of this ajax call is to send some information to the server without expecting any return value. I attempted the following approach: document.querySelector("#myId").onclic ...

Organizing multidimensional array in PHP - tackling challenges with dates and numerical order

I have this array output from PHP and I have two tasks to complete. Firstly, I need to sort the array by the most recent date. Since the date is in the format mm/dd/yyyy, a simple sort won't work for this task. Secondly, I need to determine the numbe ...

A structure array pointer in C pointing to a structure, within another structure

Struggling with pointer syntax here. I have an array of structures and am attempting to create a pointer to it from within another structure contained in an array. struct foo array* = malloc(sizeof(foo)*10); bar_arr[i]->foo_ptr = &array; After rea ...

What is the process of transforming an object into an array in C#?

jsonResult["filePath"] {[ "D\\test.pdf" ]} Is there a way to obtain the path of this file? I am having difficulty converting this object into an array. Are there any alternative methods to access this filePath? ...

The variable is constantly reverting back to its initial value

Here is the code snippet: function send() { var nop = 6; var send_this = { nop: nop }; $.ajax({ type: "GET", data: send_this, url: "example.com", success: function(r) { ...

I am confused about what my teacher wants me to do. Have I interpreted the task correctly?

I completed the assignment, but I'm still unclear if I have fully grasped my teacher's instructions. Can you provide some insight on this for me? I attempted to solve it using two arrays, a for-loop, and connecting a button with a function, and ...

Only when the user has successfully completed the reCAPTCHA and checked the checkbox, Vue will be able to

For my new project developed with VueJs, I am implementing a Single Page Application (SPA). The objective is to incorporate a simple if statement functionality. When the user checks a checkbox and successfully solves the reCaptcha, Vue should send an email ...

Is it necessary to call cancelAnimationFrame before the next requestAnimationFrame?

Within my React timer application, I am unsure if I need to always call cancelAnimationFrame before the next requestAnimationFrame in the animate method. I have come across conflicting information - one source mentioned that if multiple requestAnimationFr ...

Using Bootstrap datepicker to show dates in Month YYYY format and then sending the data to server as MMYYYY for processing

Utilizing the bootstrap datepicker to select a date has been smooth sailing so far. However, due to certain server limitations, we now need to submit the data in the format "022021" rather than "Feb 2021". How can we achieve this post-formatting and submis ...

Guide on accessing text content from a sibling div element using jQuery

There are several divs arranged on a page as shown below. If a user clicks a link within the UL .list-links, I want to capture the content inside: <span class="asa_portlet_title">Title here</span> and store it in a variable. I have attempted ...

The mysterious workings of the parseInt() function

As I begin my journey to self-teach JavaScript using HeadFirst JavaScript, I've encountered a minor obstacle. The chapter I'm currently studying delves into handling data input in forms. The issue arises when I attempt to utilize the updateOrder( ...

What steps are involved in setting up a local server on my computer in order to create an API that can process http requests from Flutter?

New to API creation here, so please be patient. I plan to eventually host my API on a more robust server, but for now, I want to get started by setting something up locally on my PC to work on backend functions. The API goals include: Verify incoming requ ...

Both the maxlenght and ng-maxlength directives appear to be ineffective in AngularJS

In my HTML file, I have the following input: <input name="password" id="newPasswordConfirmation" ng-model="newPasswordConfirmation" type="number" inputmode="numeric" placeholder="" required ...

using ng-repeat within a nested loop to iterate through objects nested within other objects

https://i.sstatic.net/eoRHo.png My goal is to replicate the image above using AngularJS ng-repeat. I am facing difficulty with the third column. <div tasty-table bind-resource-callback="showTCS.loadAllTCS" bind-init="showTCS.init" bind- ...

Analyzing nested arrays against dictionary keys

Here is the array I am working with: [[ 36 119] [ 36 148] [ 36 179] [ 67 209] [ 69 84] [ 96 240]] In addition, I have a dictionary that looks like this: {84: [36, 119], 85: [36, 148], 86: [36, 160]} My goal is to identify if any values from the arra ...