Start together by a common word (not by individual letters)

I came across this amazing sharedStart function in a challenge. You can find it here:

function sharedStart(array){
    var A= array.concat().sort(), 
    a1= A[0], a2= A[A.length-1], L= a1.length, i= 0;
    while(i<L && a1.charAt(i)=== a2.charAt(i)) i++;
    return a1.substring(0, i);
}

However, this function works on a per-character basis.

For example, using the function returns Noitidart Sab:

sharedStart(['Noitidart Sab', 'Noitidart Saber'])  //=> 'Noitidart Sab'
sharedStart(['Noitidart Sab', 'Noit'])  //=> 'Noit'
sharedStart(['Noitidart Sab', 'Noitidart Saber', 'Noit'])  //=> 'Noit'
sharedStart(['Noit Sab bye', 'Noit Sab hi there'])  //=> 'Noit Sab '

Nevertheless, I am interested in performing the comparison by word instead of character. In that case, the expected results should be as follows:

sharedStartWords(['Noitidart Sab', 'Noitidart Saber'])  //=> 'Noitidart'
sharedStartWords(['Noitidart Sab', 'Noit'])  //=> '' // for no match
sharedStartWords(['Noitidart Sab', 'Noitidart Saber', 'Noit'])  //=> '' // no match
sharedStartWords(['Noit Sab bye', 'Noit Sab hi there'])  //=> 'Noit Sab'

I have attempted to come up with my own solution, but it has become quite convoluted. It's so bad that I feel embarrassed to share it as part of the question. Can someone please guide me on how to create a sharedStartByWord version?

Answer №1

What do you think of the following solution?

function findSharedStartingWord(array){
    var newArr = array.concat().sort(),
        firstArray = newArr[0].split(/\W/), lastArray = newArr[newArr.length-1].split(/\W/),
        length = firstArray.length, index = 0;
    while (index < length && firstArray[index] === lastArray[index]) { index++; }
    return firstArray.slice(0, index).join(' ');
}

Answer №2

  • Divide all the elements in the array using a space
  • Retrieve the first element along with the rest of the elements
  • Compare each element in the remaining elements with the corresponding element in the first array element at the same index
  • If there is a discrepancy, remove that particular element from the first array

function findCommonStartWord(arr) {
  var A = arr.concat().map(el => el.split(" "));
  var B = A.concat();
  B.shift();

  var words = A[0];
  var wordsToRemove = [];

  A[0].forEach((el, i) => {
    B.forEach(_el => {
      if (el !== _el[i])
        words.splice(i, 1);
    })
  })

  return words.join("");
}

var x = findCommonStartWord(['Hello World', 'Hello Universe', 'Hello Something']);
console.log(x);

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

Implementing automatic activation of a tab upon page load using Angular

I am currently working with a set of Bootstrap nav pills in my navigation bar. The 'ng-init' code in my Angular script sets the 'dateState' to 'past' on page load. However, I have noticed that the 'Past Events' nav p ...

My attempt to reveal hidden information in my repeater using a button and JavaScript has not produced the desired results

Welcome to my first post on this forum. In the HTML code, there is a repeater containing a button shown below: <button type="button" class="btn btn-info">Contact</button> <p style="display: none" id="contact"><%# Eval("Email") %&g ...

Transferring data between JavaScript and PHP

Is there a way to transfer data from JavaScript to PHP when a button is clicked? For instance, can the getdate() function's result be sent to PHP? This transferred value will then be utilized for database manipulation. ...

Troubleshooting custom buttons error when using carousel in Nuxt app: "Flickity is not defined"

I am attempting to connect my own personalized buttons to a flickity carousel within a nuxt application. Within my carousel component, the following code is present: <template> <ClientOnly> <Flickity ref="flickit ...

Concurrent HTTP Requests - AngularJS

My directive, known as machineForm, includes a dataService: dataService.getMachineTaxesById($scope.machineId).then(function (response) { $scope.machine.machineTaxes = response.data; }); I am using this directive twice simultaneously. <div class= ...

Ways to terminate and fulfill a promise

Each time I execute this snippet of code, a promise is returned instead of the data being inserted into my database. Unfortunately, I am unable to utilize the await keyword due to it not being in a top-level function. Specifically, I receive the message: & ...

AngularJS Login Popup with SpringSecurity

I have successfully integrated spring security with my AngularJS webpage utilizing Rest API. However, I am facing an issue where every time I attempt to log in using the rest api from my customized login page, it prompts me for the login credentials in a p ...

The ng-disabled directive in Angular JS is not effectively disabling a button

Why is the button not disabled? var mainApp = angular.module('mainApp', []); mainApp.controller('mainController', function ($scope) { $scope.form = { login: '' }; }); <form ng-controller="LoginAppCtrl as ...

Is it possible to employ variable data outside the function?

As a newcomer to programming, I understand that variables inside a function cannot be accessed outside of it. However, I am in need of the object stored in 'call'. Is there any way to extract data from this object? I have attempted declaring &ap ...

Is there a way to ensure that the await subscribe block finishes before moving on to the next line of code?

My goal is to utilize the Google Maps API for retrieving coordinates based on an address. In my understanding, using await with the subscribe line should ensure that the code block completes before moving on to the subsequent lines. async getCoordinates ...

Exploring the dynamic relationship between React's useEffect and useState functions

Currently, I am working on developing a table using React and Material UI's XGrid component. The table includes buttons that execute specific actions when clicked. One of the requirements is to set the row ID upon clicking the row itself using the use ...

What is the best approach for testing a function containing document.querySelector() with unit tests?

export function calculateNavHeight() { const merchantNav = document.getElementById( 'merchant-header-main-wrapper-internal' ) const dw2Nav = document.querySelector('.cw_navbar__mainnav') let navHeight = 72 // Default Nav hei ...

Is it possible to provide unrestricted support for an infinite number of parameters in the typing of the extend function from Lodash

I am utilizing the "extend" function from lodash to combine the objects in the arguments as follows: import { extend } from 'lodash'; const foo1 = { item: 1 }; const foo2 = { item: 1 }; const foo3 = { item: 1 }; const foo4 = { item: 1 }; const f ...

Can you explain the concept of the "one true source"?

After reviewing this particular article, I came across a significant statement in the "Controlled Components" section: The integration of both can be achieved by ensuring that the React state is considered as the “single source of truth”. Can you ...

What could be causing my Bootstrap 4 modal not to appear?

<head> <meta charset="utf-8" /> {% load staticfiles %} <link rel='stylesheet' href="{% static 'homepage/css/bootstrap.min.css' %}"> <link rel='stylesheet' href="{% static 'homepage/css ...

There are currently no records matching the query for xxx on the designated model

I am encountering an error whenever I attempt to save a document using the .save() method. The error message is detailed in the title. let [post] = ( await User.findOneAndUpdate( { _id: USER_ID }, { $push: { posts: { ...

Disable the default page scrolling behavior when collapsing an accordion section in Bootstrap 4 framework

Incorporating a Bootstrap 4 accordion with an expanded body section that causes the content below to scroll up when collapsed. To address this issue, attempting to scroll to the top of the clicked header and prevent undesirable scrolling from the collapse ...

Does the DOMContentLoaded event fire only after all script tags have been downloaded?

Imagine this situation: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <title>Document</title> </head> <body> <script src="js/heavy_js_file.js" defer></script> &l ...

Warning: Invariant Violation - The specified TurboModuleRegistry.getEnforcing('RNDocumentPicker') cannot be located

I've encountered the following error in my React Native project: ERROR: Invariant Violation: TurboModuleRegistry.getEnforcing(...): 'RNDocumentPicker' could not be found. Verify that a module by this name is registered in the native binar ...

Ways to verify with Selenium WebDriver whether a website is employing Ajax technology

Currently, I am conducting Research and Development on several obscure third-party websites in order to extract page content using selenium. I am curious about how to determine whether a website is Ajax-based or non-Ajax based. Since I have no prior knowl ...