Ways to continuously monitor an array until specific criteria are fulfilled

My goal is to search for a specific item in an array called idarray and loop through it until I find a value that is not equal to -1. Once I find that value, I want to use the index to retrieve the corresponding value from another array called array.

To accomplish this, I can use various iteration methods like for, while, or forEach. In this case, I have two arrays: idarray and array. I have successfully implemented a process to determine the next data in the array and stop when reaching the final value. I can retrieve the next data as long as the corresponding id is not -1.

Here is my current implementation:

var item_tosearch = 0;
var idarray = [-1, 2, -1, 4, -1]
var array = [3, 2, 1, 0, 7];
var index = array.indexOf(item_tosearch);

if (index > -1) {
  var res = array.slice(index);
}

if (res != undefined) {
  for (let i = 0; i < res.length; i++) {
    if (res[i + 1] != undefined) {
      if (idarray[index + 1] == -1) {
        if (res[i + 2] != undefined) {
          console.log("Next = " + res[i + 2]);
          break;
        } else {
          console.log("Final index");
          break;
        }
      } else {
        console.log("Next = " + res[i + 1]);
        break;
      }
    } else {
      console.log("Final index");
    }
  }
} else {
  console.log('data not found');
}

I would like to know if there are any ways to improve this method.

Any advice is appreciated.


Clarification:

Imagine we have the following arrays:

idarray = [-1, 2, -1, 4, 1]; array = [3, 2, 1, 0, 7];

If I search for the value 2 in the idarray, I expect to receive 0 as the returned value, as it is the next item without -1 in the id.


In another scenario:

idarray = [-1, 2, -1, -1, 1]; array = [3, 2, 1, 0, 7];

If I search for the value 2 in the idarray, I expect to receive 7 as the returned value, as it is the next item without -1 in the id.

However, if the idarray is [-1, 2, -1, -1, -1] and I search for the value 2, I expect "final index" to be returned, as there are no more items without -1 as the id.

I have tried another iteration method to fetch the desired results:

var item_tosearch = 2;
var idarray = [-1, 2, -1, -1, -1]
var array = [3, 2, 1, 0, 7];
var index = array.indexOf(item_tosearch);

if (index > -1) {
  var res = array.slice(index);
}

if (res != undefined) {
  for (let i = 0; i < res.length; i++) {
    if (res[i + 1] != undefined) {
      if (idarray[index + 1] == -1) {
        for (let j = i + 1; j < res.length - i; j++) {
          if (res[j + 1] != undefined) { // fetch if still got data with id != -1
            console.log("Next = " + res[j + 1]); // should show next item without -1 in id
            break;
          } else {
            console.log("Final index"); // reach end of array
            break;
          }
        }
      } else {
        console.log("Next = " + res[i + 1]); // should show next item without -1 in id
        break;
      }
    } else {
      console.log("Final index"); // reach end of array
    }
  }
} else {
  console.log('data not found');
}

Answer №1

If I understand correctly what you're asking for, it seems like you're interested in a solution similar to this one. Even if it's not exactly what you're looking for, it could provide some inspiration.

  • This approach begins by locating the index of the element to search for in the idarray. If it's not found, the function returns undefined.
  • Then, it iterates starting from the next index until the end of the idarray. If a non--1 element is encountered, the function returns the element at the current index from the array.
  • If no matching element is found, the function returns undefined.

var idarray, array;

function findElement(item_tosearch, idarray, array) {
  var index = idarray.indexOf(item_tosearch);
  if (index === -1) return; // element not found

  for (index += 1; index < idarray.length; ++index) {
    if (idarray[index] !== -1) return array[index];
  }
  
  // end of array reached
}

idarray = [-1, 2, -1, 4, 1];
array   = [ 3, 2,  1, 0, 7];
console.log(findElement(2, idarray, array));

idarray = [-1, 2, -1, -1, 1];
array   = [ 3, 2,  1,  0, 7];
console.log(findElement(2, idarray, array));

idarray = [-1, 2, -1, -1, 1];
array   = [ 3, 2,  1,  0, 7];
console.log(findElement(9, idarray, array));

Answer №2

I believe I grasp the concept, although I am not entirely certain. The query seems to be:

Is my goal to verify if any of the ids following the id that corresponds to my value are not -1
?

I hope I have interpreted the concept accurately.

If you do not require reusable functions or do not mind the structure, you can simplify this further:

var pos = 0;
var idarray = [ -1, 2, -1, 4, -1 ];
var array = [ 3, 2, 1, 0, 7 ];

var get_result = ( array, idarray, pos, ex ) => {
  const offset = array.indexOf( pos ) + 1;
  return idarray
    .slice( offset )
    .reduce(( result, id, index ) => {
      if ( result === "final index" && id !== -1 ) result = array[ index + offset ];
      return result;
    }, "final index" );
};

// Example 1:
const ex1_search_value = 0; // pos
const ex1_ids = [ -1, 2, -1, 4, -1 ]; // idarray
const ex1_values = [3, 2, 1, 0, 7]; // array
// Expecting "final index" since our range only contains the last id, which is -1
const result1 = get_result( ex1_values, ex1_ids, ex1_search_value );
console.log( `Expecting final index, ${ result1 }` );

// Example 2:
const ex2_search_value = 2;
const ex2_ids = [ -1, 2, -1, -1, -1 ];
const ex2_values = [3, 2, 1, 0, 7];
// Expecting "final index" since our range consists of the last two items, both with id -1
const result2 = get_result( ex2_values, ex2_ids, ex2_search_value );
console.log( `Expecting final index, ${ result2 }` );

// Other examples follow...

Another method is to combine the arrays into one array containing objects, eliminating the need to check for undefined values while still utilizing array methods instead of simple loops. This approach proves beneficial when the id/value combinations are frequently used beyond this point in the code. These functions enhance reusability.

// Create an object from the id and value combinations.
const create_collection = ( ids, values ) => {
  return ids.map(( id, index ) => ({
    id,
    value: values[ index ]
  }));
};

const has_valid_descendants = ( collection, search_value ) => {
  const search_index = collection.findIndex( item => item.value === search_value );
  const collection_in_range = collection.slice( search_index + 1 );
  return collection_in_range.find( item => item.id !== -1 ) || 'final index';
};

// Example 1:
const ex1_search_value = 0; // pos
const ex1_ids = [ -1, 2, -1, 4, -1 ]; // idarray
const ex1_values = [3, 2, 1, 0, 7]; // array
const ex1_collection = create_collection( ex1_ids, ex1_values );
console.log( ex1_collection );
const ex1_result = has_valid_descendants( ex1_collection, ex1_search_value );
console.log( 'Expecting 1: "final index"' );
console.log( `Example 1: ${ JSON.stringify( ex1_result ) }` );

// Other examples follow...

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

Is there a way for me to receive a unique selection of items from an array for every accordion item?

I am currently facing an issue where all three accordion items have the same set of objects, but I want each of them to have a different set. Here's what I have attempted so far, but it is not working as expected: const meetingRooms = [ { ...

Ensure that all MongoDB write operations have been completed before proceeding with a find operation

I am in need of a store js object that can manage a mongodb collection in a specific way: store.insert(thing); // triggered from a pubsub system without waiting for the insert to complete store.get(); // should return a promise that resolves to the items ...

What could be the reason for my array parameter not being included in the POST request

When working on my laravel 5.7 / jquery 3 app, I encountered an issue while trying to save an array of data. After submitting the form, I noticed that only the _token parameter is being sent in the POST request as seen in the browser console: let todos_co ...

Guide on making a button display an image, then switch back to the initial image when clicked again

Currently, I have this neat feature on my website where there's a button that toggles the image/background color - kind of like a dark mode switch. The background change is working fine, but I'm encountering some challenges with organizing the im ...

What are the steps to resolve the issue of "npm ERR! EEXIST: file already exists, rename" occurring with non-existent files?

Welcome to my first question post. (Please be kind if I make mistakes.) I am using node version 5.6.0. For an assignment, I downloaded a JS web app but am encountering an error that is preventing me from working on it: S:\PersonalCloud\jennyly ...

Using jQuery Backstretch to generate a stunning image slideshow from the src attributes of images

I am utilizing the slideshow feature of jQuery Backstretch on my website. My plan is to use this functionality on multiple pages, each with its own unique set of images. To streamline the process, I believe it would be more efficient to extract the image s ...

How can one retrieve data from two distinct API routes within a Next.js application?

Currently, I am working with Next.js and facing a challenge in fetching data from two different API routes simultaneously. My intention is to retrieve this data within the getServerSideProps function. The first dataset that I require can be found at the e ...

What could be the reason for my form submission redirecting to the PHP page?

(I recently discovered that I could edit and reopen the post I had previously made. Feeling a bit confused about the process...) After submitting the form, the email is sent successfully, but then I am redirected to my php page displaying the number 0. Th ...

What steps should I take to resolve the eslint issue indicating that a TypeScript props interface is not being utilized, even though it is being used?

One of my components utilizes AvatarProps for its props: https://i.sstatic.net/cZBl1.png Below is the interface declaration for AvatarProps: export interface AvatarProps { userName: string; userLastName: string; userImg?: string; onPress?: Functi ...

PHP populate missing array indexes

I have an array that stores values per year and per week, retrieved from my database. The stored data may resemble the following: Array ( [2018] => Array ( [40] => 1 [41] => 1 [47] => 1 ...

Modify the color of every element by applying a CSS class

I attempted to change the color of all elements in a certain class, but encountered an error: Unable to convert undefined or null to object This is the code I used: <div class="kolorek" onclick="changeColor('34495e');" style="background-c ...

selecting a number at random from a defined array

I am looking to generate a series of lottery numbers like the following: my list could be between 1 - 100, or it might range from 1 - 200, or even 1 - 300 select 35 random numbers from the chosen list. choose another set of 25 numbers from the list. pic ...

The secret equation for unravelling an array of gridded numbers, including

I have been using this method to flatten a multidimensional array (x,y,z): array = new byte[GridSizeX*GridSizeY*GridSizeZ]; index = x + y * GridSizeX+ z * GridSizeX* GridSizeY; I am now trying to figure out how to adjust this formula to handle n ...

Dynamically showing a div using JavaScript and AJAX after changing the window location

After successfully fetching data from the server through AJAX, I am redirecting to the same screen/URL. Is it possible to show/display a div after redirecting using jQuery? $.ajax({ type: "POST", url: action, data: form_data, success: func ...

Unusual occurrences of backslashes in arrays when using JSON.stringify

While experimenting with JavaScript, I observed an unusual behavior when inserting a backslash \ into a string within an array and using JSON.stringify() to print it. Normally, the backslash is used for escaping special characters, but what if we actu ...

Sliding Toggle: Panel Revealed with Button Slide

Currently, I am working on implementing a jquery slide tab feature. The functionality is working fine on button click. However, I want the button to stick with the panel and slide along with it. At the moment, the button remains fixed while the panel slide ...

Is there a different npm package that can extract paragraph data since pdf2json npm package is not working properly?

After attempting to use the pdf2json npm package to extract data from a PDF, I found that it was not extracting the data into paragraphs as desired. I have a PDF document that includes tables, paragraphs, and charts, and I am looking to extract the raw da ...

Debugging a script designed to output a value of 1 if the Mean equals the Mode, and 0 if they are not equal

As a beginner coder, I am working on a code that should return 1 if the mean is equal to the mode and 0 otherwise. However, my current code only outputs 0 even when it should be returning 1. Any guidance or assistance in identifying where I may have made ...

What is the reason behind Google Closure Compiler appending a variable to the global namespace when the original namespace was blank?

My long script is neatly enclosed within a (function() {/.../})() to prevent any name pollution. It has been typed with complete accuracy and zero warnings. I recently discovered that Google Closure compiler initially redefines i and j in the global names ...

The specified type argument is not compatible with the ObservableInput<any> type

Struggling with an issue where the argument type (key:string) => Observable | PayloadType | is causing problems when trying to assign it to a parameter of type '(value: string, index: number) => ObersvableInput' return action$.pipe( fil ...