Replace the empty slots in the array with an underscore

Is it possible to use underscorejs to populate missing elements in an array? For example:

fillGaps([1,2,3,6,7,22,23,24]) => [1,2,3,'...',6,7,'...',22,23,24]

Answer №1

Here's how I would approach this:

function fillArrayGaps(arr) {
    for (var index = arr.length - 2; index >= 0; index--) {
        if (arr[index] < arr[index + 1] - 1) {
            arr.splice(index + 1, 0, '...');
        }
    }
    return arr;
}

This function modifies the original array directly.

Alternatively:

function fillArrayGaps(arr) {
    var resultArray = [];
    for (var index = 0; index < arr.length - 1; index++) {
        resultArray.push(arr[index]);
        if (arr[index] < arr[index + 1] - 1) {
            resultArray.push('...');
        }
    }
    return resultArray;
}

Another option is to use a less readable version using .reduce and the comma operator:

function fillArrayGaps(arr) {
    return arr.reduce(function(result, value, currentIndex, array) {
        return result.push(value), value < array[currentIndex+1] - 1 ? result.push('...') : false, result;
    }, []);
}

Answer №2

One possible approach is as follows:

const fillGaps = (arr) => {
  let result = [];
  let previous = 0;
  arr.forEach((element) => {
    if (element > previous + 1) {
      result.push('...');
    }
    result.push(element);
    previous = element;
  });
  return result;
};

However, there may be a more concise solution available.

Answer №3

alert(fillGaps([1,2,3,6,7,22,23,24]));

function fillGaps(arr) {
    var l=arr.length;
    var out=[];
    var thisel;
    var lastel=null;
    for(var i=0;i<l;i++) {
        thisel=arr[i];
        if(lastel!=null && thisel>lastel+1) out.push("...");
        out.push(thisel);
        lastel=thisel;
    }
    return out;
}

FIDDLE

You have the option to remove lastel!=null && and instead set var lastel=1; at the start. This adjustment will result in fillGaps([3,6,7,22]) returning ['...',3,'...',6,7,'...',22] (including filling the first position if it is not 1)

Answer №4

To locate the missing element in the array, utilize the inArray method. The _.last() function will fetch the final element from the array.

var arr1 = [2,5,8,9];
var arr2 = [];
for(var j=0; j < _.last(arr1) ; j++){
   if($.inArray(j+1, arr1) >= 0){
      arr2[j] = j + 1;
   } else {
      arr2[j] = "..";
   }
}

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

Tips for testing the setTimeout function within the ngOnInit using Jasmine

Could someone please assist me with writing a test for an ngOnInit function that includes a setTimeout() call? I am new to jasmine test cases and unsure of the correct approach. Any guidance would be greatly appreciated. app.component.ts: ngOnInit(): void ...

Event in javascript or jquery triggered whenever the value of a dropdown selection is altered

What options do I have when the user does not manually change a select value using JavaScript or jQuery events? For example, if I have multiple cascading selects and the user chooses a default value in one of them without triggering an event, how can I han ...

How can I retrieve the value of the Material UI pickers in my component?

How can I retrieve the value in a component after selecting a date from the date picker? Demo Link: https://material-ui.com/demos/pickers/ Here is an example: import React from 'react'; import PropTypes from 'prop-types'; import { wi ...

Discover identical HTML elements

I have a simple HTML code that I would like to split into similar parts: <input id="checkbox1"><label><br> <input id="checkbox2"><label><br> <input id="checkbox3"><label><br> The desired result should ...

Formatting database values in `where` conditions for strings in TypeORM: A simple guide

I am trying to utilize TypeORM's "exist" method in order to check if a name has already been inserted into the database. My issue is that I cannot determine whether the name was inserted in uppercase or lowercase, leading to potential false validatio ...

Transferring PHP Array information to JavaScript

I'm facing an issue with transferring data from a PHP function querying a mySQL database to a JavaScript function for use in a plotly graph. Although I can successfully retrieve the data in PHP, I encounter a problem when trying to access it in my Jav ...

Retrieving a list from a C# function using JQuery ajax

I find myself in a bit of a dilemma while attempting to integrate C# and jQuery seamlessly. Within the same solution/project, I have a .cs file and a javascript document. The C# function I've written returns a list of strings, which I aim to append to ...

Clear session data when logging out from a dropdown list

I have a header that appears on several of my web pages. It contains a dropdown menu that allows users to log out by selecting the "Logout" option. When a user clicks on "Logout", I want to destroy the session variables associated with their session. Is t ...

Is there a way for me to revert back to my initial list after the 3rd click?

Front end development const [clientList, setClientList] = useState([]); //store all data from the database in a list //make an axios request to retrieve data from the database useEffect(() => { Axios.get("http://localhost:3001/clients&quo ...

Testing a Svelte Component with Unit Tests { #conditionals }

Test Procedure Instructions To begin, execute the following bash command: mkdir example && cd example && mkdir src && touch jest.config.js && pnpm init && pnpm i @jest/globals @testing-library/svelte jest jest-envi ...

"Looking for a solution to the ESLint error related to 'no-unused-var' and Google Maps integration. How can I effectively resolve

I'm struggling with what seems to be a simple problem I tried adding /* export myMap */ or /* global myMap */ at the beginning of the script but I keep getting errors Code HTML <h1>My First Google Map</h1> <div id="googleMap" ...

Tips for transforming a scroll element into the viewport using Angular 2+

This is a sample Here is a component with a list of items: class HomeComponent { text = 'foo'; testObject = {fieldFirst:'foo'}; itemList = [ '1', '2', '3', & ...

Working with masonry does not involve filling tiny crevices

Check out the DEMO here Experience the FULL Screen DEMO An issue with Masonry: it's not filling small gaps even when there is available space. For example, in a main container with a width of 896px; next to the first container with an orange backgr ...

Using React.js to compute dates based on user-inputted dates

Today was dedicated to tackling the coding challenge of creating a function. I'm currently working on a react app using the PERN stack. The form I'm working on includes multiple date inputs, with two date columns and a total days column. My goal ...

Sorting the array in MongoDB before slicing it

Currently, I have a pipeline that aggregates Regions along with their respective countries and sales values. My goal is to obtain the top 5 countries by sales in each region using the $slice method. However, the issue I am facing is that it returns the fir ...

When generating JSON data, be sure to specify the file type as "File" rather than using

Recently, I was following a tutorial on Node.js and JSON. In the tutorial, it was mentioned that after creating a JSON object and using the filesystem (fs) module to create a JSON file by stringifying it, the file is created with the type 'File' ...

Display two elements from the array on each line, with the elements separated by a comma

Can anyone assist me with this issue? I have an array containing 6 items, and I would like to display 2 items per line separated by commas. Here is the code I am currently using: $rates[] = array("2020-01-01"=>3000); $rates[] = array("2020-01-02"=>30 ...

Iterating through the sorted list in reverse order, retrieving the text of each list item

Is there a way to navigate through an ordered list, extract and return the text based on a scenario where the user clicks on an li element like Cat 1-2? The goal is to concatenate all parent li's text into either a string or an array. If an array is u ...

Collapsed ReactJS: Techniques for compressing the Material UI TreeView following expansion

My issue involves a Material UI treeView. After expanding it, an API call is made, but the node in the treeView remains open. I have attempted to use onNodeToggle without success. Below is my code: <TreeView className={classes.root1} defaultExpandI ...

Trouble with Callback firing in Select2's 'Infinite Scroll with Remote Data' feature

After reviewing the tutorial on the Select2 project page, I am implementing a feature to load additional records as the user scrolls to the end of the results. <script> $(document).ready(function() { $('#style_full_name').select2({ ...