What is the correct way to iterate through an object, evaluate three properties, and then push them into an array?

I am tasked with creating a function called runOnRange that will populate a new array based on the properties of an object. The object contains three properties: start, end, and step. The goal is to push specific numbers into the array according to these properties and then return the array.

As a beginner, I need to stick to basic techniques like loops and conditionals.

Here are some examples that illustrate what is needed:

runOnRange({start: 10, end: 17, step: 3})

// => 10 // => 13 // => 16

runOnRange({start: -6, end: -4})

// => -6 // => -5 // => -4

runOnRange({start: 12, end: 12})

// nothing should be console.logged in this case!

runOnRange({start: 23, end: 26, step: -1})

// nothing should be console.logged in this case!

runOnRange({start: 26, end: 24, step: -1})

// => 26 // => 25 // => 24

runOnRange({start: 23, end: 26, step: 0})

// nothing should be console.logged in this case!

This is the current code implementation:

function runOnRange (object) {
    var arrNew = []
    var start = object.start
    var end = object.end
    var step = object.step

    //Case 1: steps between start and end range
    if(start + step <= end && start + step >= start) {
        for (var i = start; i <= end; i = i + step) {
            arrNew[i]=i;
        }
    }

    //Case 2: steps not set, defaulting to increment by one
    if (step == undefined) {
        step == 1;
        if(start + step <= end && start + step >= start) {
            for (var i = start; i <= end; i = i + step) {
                arrNew[i]=i
            }
        }
    }
    return arrNew
}

When running

runOnRange({start: 10, end: 17, step: 3})

the output in the console shows

(17) [empty × 10, 10, empty × 2, 13, empty × 2, 16] 

indicating there is at least one error.

Executing

runOnRange({start: -6, end: -4})

results in an empty array, whereas it should increase the steps parameter by one.

Where have I made mistakes?

Answer №1

To prevent the creation of a sparse array, it is important to increment the value of i in arrNew[i] by just one, instead of by a certain step - although utilizing push would be more convenient.

For an even simpler approach, I recommend using a basic while loop with the option to specify a step parameter that defaults to 1:

function generateNumberRange ({ start, end, step = 1 }) {
  const arr = [];
  if (step === 0) { // handling a unique case...
    return arr;
  }
  let currNum = start;
  while (start < end ? (currNum < end) : (currNum > end)) {
    arr.push(currNum);
    currNum += step;
  }
  return arr;
}

console.log(generateNumberRange({start: 10, end: 17, step: 3}));
console.log(generateNumberRange({start: 12, end: 12}));
console.log(generateNumberRange({start: 26, end: 24, step: -1}));

Answer №2

Well, this explanation does go on a bit to cover all scenarios. But the key points are

  • Use array.push instead of an index
  • Avoid unnecessary repetition; set step as 1 if it's undefined
  • Exit early if step is zero
  • Different conditions needed for step being >0 or <0.

function runOnRange(obj){
   var start = obj.start;
   var end = obj.end;
   var step = (obj.step == undefined) ? 1 : obj.step;
   var arrNew = [];
   if(step == 0) return arrNew;
   
   if((step>0 && start + step <= end && start + step >= start) || (step<0 && start + step >= end && start + step <= start)) {
        for (var i = start; (step>0 && i <= end) || (step<0 && i>=end); i = i + step) {
            arrNew.push(i);
        }
    }
    return arrNew;
}

console.log(runOnRange({start: 10, end: 17, step: 3}))
// => 10 // => 13 // => 16

console.log(runOnRange({start: -6, end: -4}))
// => -6 // => -5 // => -4

console.log(runOnRange({start: 12, end: 12}))
// nothing should be console.logged in this case!

console.log(runOnRange({start: 23, end: 26, step: -1}))
// nothing should be console.logged in this case!

console.log(runOnRange({start: 26, end: 24, step: -1}))
// => 26 // => 25 // => 24

console.log(runOnRange({start: 23, end: 26, step: 0}))
// nothing should be console.logged in this case!

Answer №3

Alright,

I believe I have found a solution in this code snippet. It may not be the most elegant or efficient, but it seems to get the job done for now.

function runOnRange (object) {
    var arrNew = []
    var start = object.start
    var end = object.end
    var step = object.step

    //Case 0: handling when step is 0
    if (step === 0) {
        return arrNew
    }

    //Case 1a: steps between start and end range, where start is smaller than end
    if(start + step <= end && start + step >= start) {
        for (var i = start; i <= end; i = i + step) {
            arrNew.push(i)
        }
    }

    //Case 1b: steps between start and end range, where start is higher than end
    if(start + step >= end && start + step <= start) {
        for (var i = start; i >= end; i = i + step) {
            arrNew.push(i)
        }
    }

    //Case 2: default case where step is not set, increments by one
    if (step == undefined) {
        step == 1;
        if(start + step <= end && start + step >= start) {
            for (var i = start; i <= end; i = i + step) {
                arrNew[i]=i
            }
        }
    }
    return arrNew
}

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

Utilizing UTC Time with AngularUI's UI-Date Datepicker

My issue lies with the datepicker using localized time instead of UTC when making calls to the backend. To handle this, I've created a function that adjusts the value before posting it to the server: function adjustDateForTimeOffset(dateToAdjust) ...

Tips for efficiently updating state within a loop using the settimeout function in a React application

As I work on my react app to visualize sorting algorithms, I've encountered an issue that has me stumped. I am currently iterating through all elements of the array stored in the 'bars' state and attempting to swap them for testing purposes. ...

Unable to use the same hexadecimal HTML entity in the value props of a React JSX component

Can someone explain why this code snippet displays dots as password and the other displays plain hexadecimal codes? <Field label="Password" value="&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;" type="password" /> While this one disp ...

jQuery's show/hide functionality allows for the dynamic resizing of images,

I am experiencing an issue with a Joomla template that has a custom jQuery menu. When I hover over the map with my mouse, the overlay appears slightly larger than expected. This problem seems to be occurring in Firefox and IE 11, leading me to believe it ...

Guide on activating javascript code for form validation using php

How can I activate JavaScript code for form validation? I am currently implementing form validation on a combined login/register form where the login form is initially displayed and the register form becomes visible when a user clicks a button, triggering ...

Using D3.js for Page Navigation

For my D3 bar charts, I am working with a substantial amount of JSON data obtained from an API. My goal is to display only 10-20 bars at a time. Would it be possible to implement pagination using D3 itself, or should I explore alternative methods (such a ...

ReactJs Unicode Integration with ID3 JS

I am working on a React Project that involves using an input type = "file" to upload music files. I am able to extract tags using ID3 Js, but the result is displayed in this format: https://i.stack.imgur.com/192co.png Is there a way to convert ...

Issue with the back-to-top button arises when smooth-scrolling feature is activated

This Back To Top Button code that I discovered online is quite effective on my website. // Defining a variable for the button element. const scrollToTopButton = document.getElementById('js-top'); // Creating a function to display our scroll-to- ...

Unable to align text within a DIV using CSS

Recently, I started learning jQuery and building my own website. You can find my project on JSFIDDLE. The issue I'm facing is that when hovering over a new div, the text extends beyond the borders of that div instead of staying within it. I've sp ...

What is the process for activating namespacing on a VueX module that has been imported?

I am currently utilizing a helper file to import VueX modules: const requireModule = require.context('.', false, /\.store\.js$/) const modules = {} requireModule.keys().forEach(filename => { const moduleName = filename ...

Exploring the process of retrieving array elements from an AJAX response transmitted from PHP

Here is an example of jQuery code for an ajax function: $(document).ready(function() { $("#zip_code").keyup(function() { var el = $(this); var module_url = $('#module_url').val(); if (el.val().length === 5) { $.ajax({ ...

Is it possible to multiply specific values in an array based on certain conditions in another array, and then store the results in a new array?

Designing a program that utilizes arrays to calculate stipends for tutors assisting students with their skills. The user inputs the number of tutors, followed by each tutor's name, number of students assisted, and degree level (BS, MS, PhD). Payment v ...

Find distinct elements in an array of objects

Imagine you have an array filled with different objects: var itemsArray = [ {name: "apple", color: "red", weight: "100g"}, {name: "banana", color: "yellow", weight: "120g"}, {name: "apple", color: "red", weight: "100g"}, {name: "banana", color: "y ...

Asynchronous task within an if statement

After pressing a button, it triggers the check function, which then executes the isReady() function to perform operations and determine its truth value. During the evaluation process, the isReady() method may actually return false, yet display "Success" i ...

The AngularJS directive seems to be having trouble receiving the data being passed through its scope

Check out this HTML code snippet I created: <div ng-controller="ctrl"> <custom-tag title = "name" body = "content"> </custom-tag> </div> Take a look at the controller and directive implementation below: var mod = angular.mod ...

Retrieving and storing information from a form without the need to submit it

I have been given the task of creating a load/save feature for a complex form. The goal is to allow users to save their progress and resume working on it at a later time. After much consideration, I have decided to implement server-side storage by saving ...

Is it possible to import data into a script?

When working with Angular, I am attempting to: $scope.data = "<script> alert('hi'); </script>"; Unfortunately, this approach does not seem to be effective. I also experimented with adding ng-bind-html but did not achieve any success ...

Divs animated with jQuery keep on moving even after the animation has finished

My current project involves animating a single circle that scales, collides with two nearby circles, and then causes those circles to animate to specific positions. While everything works as expected, there is an issue where the two circles involved in the ...

Exploring the concepts of closure and scope

It seems that the function inResult always returns false and the loop is not being executed, probably due to a lack of understanding of closures. However, I can confirm that the result variable contains the correct properties. function hasId() {return ...

What could be the reason behind npm trying to utilize a package version that is not specified in my package.json file?

My Angular and .NET 5 web application is encountering an issue when trying to install packages using the command npm i. The error message that appears is: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While re ...