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]
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]
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;
}, []);
}
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.
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;
}
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)
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] = "..";
}
}
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 ...
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 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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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" ...
This is a sample Here is a component with a list of items: class HomeComponent { text = 'foo'; testObject = {fieldFirst:'foo'}; itemList = [ '1', '2', '3', & ...
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 ...
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 ...
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 ...
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' ...
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 ...
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 ...
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 ...
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({ ...