What is the best way to incorporate a specific item using javascript?

I have an array with the following elements:

https://i.sstatic.net/6YzUp.png

Once I encounter 'finished', I split it and aim to showcase, for each string containing 'Getting', its corresponding links with 'HTTP_404'

This is my current code :

 var input = ['urlGettingF', '├─BROKEN─aquaHTTP_404', '├─BROKEN─url1HTTP_404', 'ok', 'urlok', 'Finished',
               'urlGettingF2', '├─BROKEN─url1HTTP_404', '├─BROKEN─url21HTTP_404', 'Finished',
               'urlGettingF3', 'url3ok', 'ok', 'Finished',
               'urlGettingF4', 'url4ok', 'ok', 'Finished'
              ];

  var inputDecouped = [];
  let Test=[];
  let start = '';
  let pageGetting='';
  let liens =[];
  let pages=[];
  let ok= false;
  let reference = {};
  let grouped = {};
  // Function to split the input into multiple arrays based on 'Finished'
  function ArrayToMultipleArrays(array) {
    let result = [[]];
    let index = 0;
    array.forEach((x, i) => {
      //console.log(index, i, x)
      // We will create arrays based on the value of x
      result[index].push(x);
      if ((i + 1) < array.length && x.includes('Finished')) {
        index++;
        result[index] = [];
      }
    });
    return result
  }
  
  inputDecouped = ArrayToMultipleArrays(input);
  for(let i=0; i<inputDecouped.length; i++){
    for(let k = 0 ; k< inputDecouped[i].length; k++ ){ 
      if(inputDecouped[i][k].indexOf('Getting') > -1 || inputDecouped[i][k].indexOf('HTTP_404') > -1 ){
       if(inputDecouped[i][k].indexOf('Getting') > -1 ){
         start = inputDecouped[i][k];
         pageGetting = start;
         ok= true
         //pages.push(({id:i, page: inputDecouped[i][k]}));
       }
      else if(inputDecouped[i][k].indexOf('HTTP_404') > -1 ){
        if(ok === true){
          liens=[];
          ok = false;
        }
        liens.push(inputDecouped[i][k]);
       }
      } 
   } 
  
       Test.push(({page:pageGetting, lien: liens}));
  
   
  }
  
  console.log(Test);

Upon execution, the output shown is:

https://i.sstatic.net/l0133.png

However, I desire the resulting output to be as follows:

[[object Object] {
  lien: ["├─BROKEN─aquaHTTP_404", "├─BROKEN─url1HTTP_404"],
  page: "urlGettingF"
}, [object Object] {
  lien: ["├─BROKEN─url1HTTP_404", "├─BROKEN─url21HTTP_404"],
  page: "urlGettingF2"
}]

My jsbin snippet can be found here : https://jsbin.com/loqagekiji/edit?js,console

What changes should be made to rectify this issue?

Answer №1

After experimenting with your jsbin, I was able to achieve the desired outcome by substituting

Test.push(({page:pageGetting, lien: liens}));

with

if (!ok) {
  Test.push(({page:pageGetting, lien: liens}));
}

Answer №2

Here is a helpful solution.

var input = ['urlGettingF', '├─BROKEN─aquaHTTP_404', '├─BROKEN─url1HTTP_404', 'ok', 'urlok', 'Finished', 'urlGettingF2', '├─BROKEN─url1HTTP_404', '├─BROKEN─url21HTTP_404', 'Finished', 'urlGettingF3', 'url3ok', 'ok', 'Finished', 'urlGettingF4', 'url4ok', 'ok', 'Finished'];

let record = []
const result = input.reduce((prev, curr) => 
    (((/^Finished$/.test(curr) && /HTTP_404/.test(record[1])) 
        ? ((prev = [...prev, { link: [record[1], record[2]], page: record[0] }]), (record = []))
        : (record.push(curr))), 
     prev),[])
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

Whenever I'm rendering my handlebars template, it unexpectedly gets terminated on its own

I have encountered an issue with my handlebar template. For some reason, a closing tag is being automatically inserted just before any closing tag in the template, causing it to be recognized as plain text. If you visit the following page: For example: { ...

NodeJS encountered a SyntaxError while trying to export the 'routes' object as

const paths = (app) => { app.route('/contact') .get((req, res, next) => { // middleware console.log(`Request from: ${req.originalUrl}`) console.log(`Request type: ${req.method}`) next(); }, (req, res, next) = ...

jqGrid is failing to display basic JSON data properly

As a newcomer to Jquery and Json, I am struggling with binding a JSON object from a RESTful Webservice written in WCF to jqGrid. Despite saving the JSON object as a static file and attempting to bind it to the grid, I realized that the issue does not lie w ...

When attempting to start a new React Native project using npx, I encountered an error stating "react-native: command not found"

After running 'npx react-native init MyProject' for the first time, it prompted that react-native would be downloaded, but I mistakenly terminated the process. Now, when I try again, it shows an error saying 'react-native: command not found& ...

Creating a line between two points in raphael

Hello there, I'm looking to create a line between two points in Raphael. Could you please provide me with some examples or guidance on how to achieve this? Thanks a lot!) ...

Creating a React component that allows for pagination using data fetched from a

I have a Spring Boot endpoint that retrieves and lists items from a database: @RequestMapping(method = RequestMethod.GET, value = "/task", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<?> processTask(@Valid TaskSearchP ...

Angular2: dynamic spinner directive for showing progress/loading overlay

Struggling to implement a loading indicator/overlay in Angular2 that can be added to any container div. When the boolean property isLoading changes, I want the div to grey out and display a spinning indicator, then revert back when the property changes. I ...

d3.json is unable to parse a value of 'Infinity

My goal is to retrieve data from an SQLite database and convert it into JSON format for use with d3.js in order to create a graph. I have successfully obtained this data in JSON format using the following URL: http://localhost:8085/SQLQuery/?date1=2019-03 ...

Instructions on how to adjust the modal width in react-responsive-modal?

Is it possible to adjust the width of the modal in react-responsive-modal? <div style={{width: '600px'}} > <Modal open={open} onClose={this.onCloseModal} closeOnOverlayClick={true}> <CreateSubmenu onFormSubmit={this.o ...

Efficient method for generating a pairwise distance matrix among rows of a two-dimensional array in record time

Currently, I am facing an issue with the performance of my code. Using a string in np.array leads to N^2 complexity and for a matrix with 10k rows and 10 columns, it takes more than 1 hour to execute, which is unacceptably slow. However, I am at a loss on ...

Identify the distinct elements within the array following content validation

Given this basic array: let result = ["doc1.rtf","doc2.rtf","test/doc4.rtf","test/doc4.rtf","test/doc6.rtf"] To find unique occurrences, you can use the following: let unique = [...new Set(result)]; This will give you: ["doc1.rtf","doc2.rtf","test/doc4.r ...

obtain the object type within the prototype function

Does anyone know how to retrieve the type of an object under the prototype property? For example, consider the following code: Object.prototype.someproperty = function(){ ...do something... console.log(typeof this); ..more... } In my code, "Function" al ...

Can you please provide a detailed list of all the events that are compatible with the updateOn feature in Angular's ngModelOptions?

The reference documentation notes the following: updateOn: a string that specifies which event should be bound to the input. Multiple events can be set using a space delimited list. There is also a special 'default' event that aligns with the ...

Troubleshooting: The issue of Vue (v-on) not recognizing my function

I am brand new to Vue and JS, so please bear with me as I ask some "silly" questions. Within my Vue-Pet-Project, I have implemented a self-authored class module called Sudoku. In this module, I aim to find solutions using backtracking. Upon clicking the " ...

Send information through a form by utilizing a personalized React hook

I'm having difficulty understanding how to implement a hook for submitting a form using fetch. Currently, this is what I have. The component containing the form: const MyForm = (): ReactElement => { const [status, data] = useSubmitForm('h ...

The KeyboardAvoidingView disrupts the structure of the flexbox layout

Check out this code snippet: return ( <KeyboardAvoidingView style={{ flex: 1 }} behavior="padding" enabled> <View style={style.flex1}> <View style={style.imageContainer}> <Image style={style.image} ...

Authentication for single-page applications using the Angular framework and Play Framework in the Java programming language

I'm seeking guidance on how to design an authentication mechanism using Angular front-end and Play Framework (Java) back-end. Here's the basic concept: Angular sends a REST authentication call to the Play Framework. Play generates a token and s ...

Instructions for submitting a displayed content box depending on the chosen option from a dropdown menu

Having two divs and a dropdown, I can display divs based on the dropdown selection. When the page initially loads, option1 in the dropdown and div1 are displayed by default. The issue arises when I select option2, fill in details in div2, and submit the pa ...

JQuery grid pagination bar mysteriously missing

I'm having an issue with a Jquery grid that is built on an HTML table. I've properly configured the grid properties, including implementing pager functionality with a page size of 10. However, I am unable to see the page up and page down buttons ...

Having trouble with Jest tests after transitioning to TypeScript

After transitioning my project from vanilla JavaScript to TypeScript, I encountered a strange issue with some test cases breaking. Despite everything running smoothly before the switch, certain tests using Vue.js, vue-test-utils, and jest are now failing. ...