Locate the midpoint index of the initial sequence occurrence within an array

I am trying to determine the midpoint of the first sequence that appears when given multiple strings in a large array

For example:

var array = ["c6dafc", "c6dafc", "1d2129", "1d2129", "1d2129", "cfcfff", "cfcfff", "ffffff", "1d2129", "1d2129", "1d2129", "1d2129"]

Calling function: (find center index based on 1d2129, if not found then search for 32cd32)

var result = somefunction(["1d2129", "32cd32"]);

In the example above, the result should be 3 because the first occurrence of 1d2129 is at index 2 and the last is at index 4 not 11. If 1d2129 does not appear, then it should search for 32cd32.

Note: if the number of occurrences is odd, return the center index; if even, return centerPoint - 1

Answer №1

1) Traverse through a list of search terms
2) For each term, identify the first instance. If found, locate the last occurrence in the sequence.
3) Determine the middle occurrence between the first and last indexes.
4) If no occurrences are detected, proceed to the next search term.

const customFunction = (data, arr) => {
  let i = 0;
  while (i < arr.length) {
    const searchTerm = arr[i];
    const firstIndex = data.findIndex(item => item === searchTerm);
    if (firstIndex > -1) {
      let lastIndex = firstIndex;
      while (data[lastIndex + 1] === searchTerm) {
        lastIndex++;
      }
      return Math.floor((firstIndex + lastIndex) / 2);
    } else {
      i++;
    }
  }
  return -1; // not found
};

var array = [
  "c6dafc",
  "c6dafc",
  "1d2129",
  "1d2129",
  "1d2129",
  "cfcfff",
  "cfcfff",
  "ffffff",
  "1d2129",
  "1d2129",
  "1d2129",
  "1d2129"
];

var result = customFunction(array, ["1d2129", "32cd32"]);

console.log(result);

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

Displaying multi-dimensional arrays through the console in JavaScript and showcasing their elements

My array is supposed to have 140 indexes in a single format like this: array:[0-140] //however, it currently appears as: array: [ 0: [0-99], 1: [100-140] ] I've confirmed multiple times that it is just one array of objects. Why is it s ...

Plugin refresh after callback

I have a webpage that features a row of buttons at the top, followed by some content below. Whenever one of the buttons is clicked, the content is updated using UpdatePanels. Within this content, I am attempting to incorporate the royal slider plugin, wh ...

Issue with CORS on Next.js static files leading to broken links on version 10.1.4

Currently, my Nextjs application is fetching its static files from Cloudfront. During deployment, I upload the /static folder to S3. After updating to version 9, I encountered a strange problem where some of my CSS files are triggering a CORS error: Acces ...

Challenges with TypeScript build in DevOps related to Material UI Box Component

Currently, I am facing an issue while trying to build a front end React Typescript application using Material ui in my build pipeline on Azure DevOps. The problem seems to be related to the code for the Material ui library. Despite successfully building th ...

A guide on implementing a .click function with jQuery

I have a code snippet that is supposed to add 100 to a number in a MySQL table when a button is clicked. However, the code does not work as expected. When I click the button, nothing happens, but if I refresh the page, it adds 100 to the number. Can some ...

Is it possible to change button behavior based on input values when hovering?

Currently, I am attempting to create a webpage where users can input two colors and then when they press the button, a gradient of those two colors will appear on the button itself. <!doctype html> <html> <head> <script src=&apos ...

I am encountering a nullpointerexception and the root cause of it remains elusive to me

The primary aim of the program is to create a tree-like nondeterministic automaton structure that stores information about keys and the subsequent parts of the automaton. This automaton is designed to identify patterns within a given text. While my explana ...

Issue: A malfunction was encountered during the rendering of the Server Components

Whenever I deploy my application to Vercel, I encounter the following error: production An error occurred in the Server Components render. The specific message is omitted in production builds to avoid leaking sensitive detail This issue only manifests on ...

Tips for deactivating a single edit button

Is there a way to make it so that when I click on a checkbox, only that specific todo's edit button is disabled? Currently, clicking on a checkbox disables all edit buttons in the todo list. Any suggestions? class App extends Component { state ...

How to unfurl a column with arrays of JSON data in Pandas

In my postgresql database, I have a table called a_table with one column named previous_names, stored as an array of json data using the following schema: CREATE a_table (..., previous name JSON [], ...). To fetch this table and load it into a pandas Data ...

Strange Phenomenon in Node/Express.js: Vanishing Array Elements

My goal is to extract information from a database and store it in an array for further processing. However, I am facing an issue where the elements disappear after being added in a for-loop, resulting in an empty array. // PROBLEM: all_prices-elements dis ...

bringing in a js file with an import statement at the beginning

I am looking to import a file that brings in another file for use across multiple pages Here is my folder structure: js modules momentum-scrolling index.js about.js contact.js Contents of momentum-scrolling.js: import LocomotiveScroll from &a ...

AngularJS uses two ng-repeat directives to manage and manipulate data in

I'm implementing a feature where I have two views in my HTML5 code that display the same list. <div class="list" data-ng-repeat="item in model.items"> <div class=list-item"> {{ item.name }} <a data-ng-click="addToLi ...

The concealment of the container is ineffective when attempting to hide it until all cached images are

My website has a background and a main container. I wanted to hide the container until the entire page had loaded, so I included #cover{opacity:0} at the beginning of the page and $(window).load(function() { $('#cover').css('opacity&apo ...

What is the method for obtaining the 2D coordinates (x, y) from a sorted 1D list ranging from 0 to n, considering the width and height provided?

Given a 1d list storing the indexes of an image as 0,1,2,3,4,5 ....(w*h) instead of (0,0), (0,1),(0,2)...(w,h) (where w and h are the width and height of the image), how can we determine the corresponding indexes (x,y) for a specific index like 57? It sho ...

Utilize Node.js and Java to fetch MQTT data in an asynchronous manner

I have been working on a project to create a publish/subscribe application where a Java program acts as the publisher and a NodeJS program as the subscriber. The Java client connects to an MQTT server and sends random data, while the NodeJS client subscrib ...

Automatically reload a particular webpage upon closing a pop-up window (using jQuery)

I am facing an issue with a pop-up named PopUp1 on page0.aspx. The problem occurs when a user clicks on a row in the GridView within PopUp1, causing another pop-up to launch, loading my page1.aspx. The complication arises when the user navigates through l ...

Utilizing React.js components for Parsing JSON Objects

As a beginner in reactjs, I am faced with the challenge of parsing JSON response fetched from an API in index.html and passing it to a component called Card.js as props. Despite being able to access the response in the console log, I am unable to render it ...

When utilizing the array.push method, new elements are successfully added, however, it appears to also overwrite the last object

I'm encountering a strange issue where every time I push an object to the array, the array's length increases as expected. However, the object that I push last ends up overriding all other objects. I can't seem to figure out my mistake, so p ...

Mastering the art of utilizing callback functions

As a newcomer to Javascript and Jquery, I am still learning the basics. One thing that confuses me is how javascript executes each line as it encounters it. In a certain scenario (when my value is greater than 9), the custom alert will trigger and the wind ...