Identify distinct prefixes and eliminate them from an array of strings

If you have an array of strings in Javascript, is there a way to identify the common prefix among all the strings and then remove that prefix from each string?

For instance:

["05098701", "05012302", "0545621", "0509301"]

The common prefix in this case would be "05"

The resulting array after removing the common prefix would be

["098701", "012302", "45621", "09301"]

Answer №1

Searching like a human means checking with one character, then two, and so on until finding the common prefix in an array.

To achieve this, you can utilize the remove function to strip the prefix from each array item. This process can be accomplished by employing the map method along with a callback function.

array = ["05098701", "05012302", "0545621", "0509301"]
function longestCommonPrefix(arr){
    var sortArr = arr.sort();    
    var arrFirstElem = arr[0];
    var arrLastElem = sortArr[sortArr.length - 1]; 
    var arrFirstElemLength = arrFirstElem.length;     
    var i= 0;
    
    while(i < arrFirstElemLength && arrFirstElem.charAt(i) === arrLastElem.charAt(i)) {
      i++;
    }
    
    return arrFirstElem.substring(0, i);
}

prefix = longestCommonPrefix(array);
array = array.map(function(item){
    return item.substring(prefix.length, item.length);
});
console.log(array);

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

How to programmatically close a Bootstrap modal without using jQuery in JavaScript

Is there a way to make it so that I can close a Bootstrap modal with just one click instead of having to double click? Thanks! This is the code I'm currently using to close the Bootstrap modal using JavaScript: // To Close Modal document.getE ...

Guide to building a hierarchical data object with JavaScript

Prior This object consists of multiple rows: { "functions": [ { "package_id": "2", "module_id": "2", "data_id": "2" }, { "package_id": ...

Issue: The element [undefined] is not recognized as a valid child of the <Routes> component. Only <Route> or <React.Fragment> components are allowed as children of the <Routes

I am facing an issue while trying to upgrade react-router-dom from v5 to v6. The error message I receive is as follows: Error: [undefined] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragm ...

What is the process for connecting an Angular .ts file with an existing HTML page?

As I finish up the html pages for my website, I find myself in need of integrating Angular to complete the project. My experience with Angular so far has been with ionic apps, where the CLI generates the html, ts, and css pages. However, I am curious if ...

Implementing setDoc with Firebase-Admin using Typescript in Firestore

I'm having issues with my code in config/firebase.ts: import { initializeApp, cert } from 'firebase-admin/app'; import { getFirestore } from 'firebase-admin/firestore' const firebaseAdminApp = initializeApp({ credential: cert( ...

Determine the availability of a distant website through AJAX requests

My website runs PHP's cURL to check the online status of 5 different URLs, however, this process tends to slow down the page load time significantly, especially if one of the sites being checked is not working. Someone suggested using jQuery's a ...

What is the best way to use an object as a key to filter an array of objects in JavaScript?

My data consists of an array of objects: let allData = [ {title:"Adams",age:24,gender:"male"}, {title:"Baker",age:24,gender:"female"}, {title:"Clark",age:23,gender:"male"}, {title:"Da ...

Ways to show a div element within an input field?

I want to incorporate tags similar to stackoverflow on my website. Users will be able to create tags for filtering results, searching, showcasing expertise, and more. I have managed to create tags, but I am struggling to display them inside an input box l ...

There are times when window.onload doesn't do the trick, but using alert() can make

I recently posted a question related to this, so I apologize for reaching out again. I am struggling to grasp this concept as I am still in the process of learning JavaScript/HTML. Currently, I am loading an SVG into my HTML using SVGInject and implementi ...

Explaining the process of assigning arguments to a char array in code

Can someone explain the code snippet below to me? Specifically, what is the significance of the line *line++ = '\0'; in the parse function? How does it differ from line[i] = '\0' and i++;? Furthermore, what does *argv++ = lin ...

Live streaming updates directly from Firebase

In order to achieve real-time updates from Firebase, my objective is to retrieve comments from Firebase and display them on this.note. I seem to have made a mistake in the update() function. Here is the tutorial I followed: link. methods: { update(){ db.c ...

How can a JavaScript map be created with string keys and values consisting of arrays containing pairs of longs?

Struggling with JavaScript data structures, I am trying to create a map in which the key is a string and the value is an array of two longs. For instance: var y = myMap["AnotherString"]; var firstNum = y[0][0]; var secondNum = y[0][1]; // perform opera ...

Unable to assign image src to a dynamically generated div

My current task involves setting the background URL of a dynamically created div in JavaScript, intended for use with the jQuery Orbit slider. Below is my approach: var content1 = null; $("#featured").html("<div id='content' style='&apos ...

Managing promises with mongoose - Best practices

I am new to using mongoose and I am trying to figure out how to save and handle promises in Node.js using a mongoose schema. In the example below, I am attempting to save data to a collection and handle any errors that may occur. model.js var mongoose = ...

Reading a JSON file stored within the project directory on iPhone PhoneGap using JavaScript

I need to access a JSON file stored in a project folder. Currently, I am using the following code: var obj = "www/places.json"; Can someone help me figure out how to read a JSON file located in the project folder www when working with iPhone PhoneGap an ...

Experiencing difficulties with parsing JSON data and storing values in a database

I received a JSON response from the server and need help saving the values in a MySQL database using PHP. Can someone please assist me with this? {"fields":[{"label":"Do you have a website?","field_type":"website","required":false,"field_options":{}," ...

What is the process for implementing a version folder for my @types/definition?

Is there a way to access the typings for react-router in my project? My package.json file currently has this dependency: { "@types/react-router": "^4.0.3" } However, it seems to be using the standard index.d.ts file from DefinitelyTyped library which i ...

Building a Node.js API using Express and MySQL that incorporates a search parameter functionality, which is applied only when set and allows for a combination of

I am looking to enhance my search functionality by allowing for a partial match on the 'first_name' column. Specifically, I want to be able to search for names that contain the input provided in the URL. Here is an example of the URL that curren ...

Display corresponding div elements upon clicking an HTML select option

Is there a way to make a div visible when a corresponding select option is clicked, while hiding others? My JavaScript skills are lacking in this area. CSS #aaa, #bbb, #ccc { display:none; } The HTML (I'm using the same id name for option and d ...

Dealing with Database Timeout in Express JS

I have been trying to extract SQL query execution into a separate file to prevent code repetition, but I am facing timeout issues during execution. var mysql = require('mysql'); const connectionData = { host: 'localhost', user: ...