Algorithm Falsy Bouncer in CodeCamp

What is the reason this works for all falsy values except null?

 function bouncer(arr) {
  for(let i = 0; i < arr.length; i++){
    if(!arr[i]){
      arr.splice(i,1);
      i = 0;
    }
 }
   console.log(arr);
}

bouncer([false, null, 0, NaN, undefined, ""])

Answer №1

When working with a for loop, the final expression that occurs, such as i++ in this case, will always be executed after the loop body. This means that regardless of the input array, the value of i will be reset to 0 only at the beginning of the first iteration:

function bouncer(arr) {
  for (let i = 0; i < arr.length; i++) {
    console.log('i:', i);
    if (!arr[i]) {
      arr.splice(i, 1);
      i = 0;
    }
  }
  console.log(arr);
}

console.log(bouncer([false, null, 0, NaN, undefined, ""]));

To address this, you could reset i to -1 instead, causing it to become 0 again at the start of the next loop iteration:

function bouncer(arr) {
  for (let i = 0; i < arr.length; i++) {
    console.log('i:', i);
    if (!arr[i]) {
      arr.splice(i, 1);
      i = -1;
    }
  }
  console.log(arr);
}

console.log(bouncer([false, null, 0, NaN, undefined, ""]));

Alternatively, you can simplify the logic by using .filter instead. The .filter method provides a more straightforward solution:

const bouncer = arr => arr.filter(Boolean);
console.log(bouncer([false, null, 0, NaN, undefined, ""]));

Answer №2

alternatively, you have the option to utilize

function filterFalsy(arr){
  return arr.filter(Boolean);
}

Answer №3

Adding to the input from DeterminedExpert, another approach is to manage the increase of i within the loop itself, as shown below:

function filterFalsyValues(arr)
{
  for (let i = 0; i < arr.length;)
  {
    console.log('i:', i);

    if (!arr[i])
      arr.splice(i, 1);
    else
      i++;
  }

  return arr;
}

console.log(filterFalsyValues([false, null, 0, "Another value", NaN, undefined, ""]));

Answer №4

When using arr.splice(i,1), keep in mind that the value of i is the same as the outer loop. Therefore, setting it to 0 will not be effective. To ensure the correct deletion, subtract 1 from i like this: arr.splice(i--,1) so that the shifted entry is not overlooked.

function filterFalsy(arr) {

  for(let i=0; i < arr.length; i++){
  
    if(!(arr[i]))
      arr.splice(i--,1);
  }   
  return arr;
}

console.log(filterFalsy([false, null, 0, NaN, undefined, ""]));

Answer №5

const filterFalsyValues = (arr) => {
    return arr.filter(item => item);
}
console.log(filterFalsyValues([false, 0, null, NaN, undefined, ""]));

This function filters out falsy values from an array based on their truthiness.

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

The .load() function seems to have a problem with my slider widget

I am facing an issue with a slider on my page that displays posts from a specific category. When the user clicks on "next category", the content slides to the left and new content is loaded along with its respective slider. The problem arises when the loa ...

accessing information from webpage using hyperlink reference

This seems to be a rather straightforward issue, but unfortunately, I lack the necessary expertise to address it. Despite conducting thorough research, I have been unable to find a solution - mainly because I am uncertain about what specific terms or techn ...

How can I handle pings in Discord using discord.js?

I've been working on a feature in my discord.js bot that responds to pings, but I'm running into issues. Even after trying <@BOTID> and @BOT#0000, the functionality is not behaving as expected. Here's the snippet of code I'm using ...

Allow JavaScript to determine whether to link to an internal or external web address

Currently, I am in the process of setting up a new website and need to create an HTML page with some JavaScript that can determine whether to link to the external or internal IP address. I have researched some JavaScript code to fetch the IP address, whic ...

Angular Directive may encounter compatibility issues in Internet Explorer

My journey into learning AngularJS has led me to successfully create a web application using Google Charts and Angular. Everything was running smoothly in Firefox and Chrome until I decided to test it in Internet Explorer (IE) and discovered that my projec ...

Avoiding Undefined Function Calls in php by Verifying if a String is Non-Empty

I have a String within a two-dimensional Array as shown below. $array[$i][$k]; My goal is to change the color of the string whenever it contains "SA" but not "SAP" or "Schulaufgabe" OR "Unterrichtsende" if ($array[$i][$k].includes("SA") && !$array[$i][$k] ...

Function for Sorting Including Children

I have a function that sorts divs numerically by class, but it doesn't consider children when grabbing the data. Here is the current function: $(document).ready(function () { var sortedDivs = $(".frame").find("div").toArray().sort(sorter); $.each ...

jqGrid: What could be causing the events I defined for grid edit to not fire?

I've been attempting to make in-line edits on a grid, but it seems like none of the events connected to those edits are being triggered. I am specifically looking to use afterSubmit: so that it triggers after the user has edited the Quantity field in ...

Strategies for sending information to the server via ajax and PHP differ. Simply typing $_POST['data'] may not yield the desired result

I am trying to send some information from an HTML form to the server using a PHP script before submitting it. The process involves using the .ajax() jQuery function. Below is my demo.html code: <script src="https://ajax.googleapis.com/ajax/libs/jquery ...

The AJAX success callback function failed to execute in cases where the dataType was set to JSONP during Cross domain Access

type = 'math'; var ajurl = "sample.com&callback=myhandler"; var datas = "cateid=" + cateid + "&type=" + type + "&pno=" + pno + "&whos=" + whos; $.ajax({ type: "GET", url: ajurl, data: datas, contentType: "application/json; ...

Middleware in Expressjs ensures that variables are constantly updated

I'm attempting to accomplish a straightforward task that should be clear in the code below: module.exports = function(req, res, next) { var dop = require('../../config/config').DefaultOptions; console.log(require('../../config/ ...

Instructions on creating a non-editable text area where only copying and pasting is allowed

I am looking to simply copy and paste content into a textarea without needing to make any edits within the field. <form action="save.php" method="post"> <h3>Text:</h3> <textarea name="text" rows="4" cols="50"></textarea ...

Serve the mobile version to mobile visitors and the desktop version to all other visitors

Can someone please explain to me how I can display the Mobile Version of a website when visiting on my phone, and the Desktop Version when viewing on anything larger than 500px? I have separately created both a Mobile Website and a Desktop Website. Is it ...

Tips for utilizing the fieldinfo parameter in text-to-column code with Blue Prism

Attempting to utilize the text to columns code in the blue prism code stage, I have successfully implemented it, but my results are in xlGeneralFormat instead of text format Dim wb, ws As Object Dim excel, sheet, range As Object Try wb = GetWorkbook(Hand ...

Utilizing AJAX to input information into the database with Magento

I'm just starting to learn about ajax and I may be approaching this problem incorrectly. Essentially, I have a javascript variable that needs to be added to the database. Here is what I have so far... onInit: function() { window.fcWidget.on(&apos ...

Transfer vertices into a texture and send it to the shader for processing

Finally found some time to experiment with shaders, but I hit a roadblock. My goal is to pass vertices to a shader and perform general-purpose computing on them. It seems like the gpgpu functionality is working fine because I can see a few pixels being sh ...

Setting up a ReactJS application in a development environment with a proxy

After working with React for over a month, our project requires API service calls to run on one port (81) and the web on another port (80). In my local development setup, I've been able to successfully use a proxy to make API calls which have been wo ...

Exploring the possibilities of node-webkit: node-odbc encounters a setback

Currently, I'm in the process of developing a desktop application utilizing node-webkit. The main functionality of the app involves querying an Oracle database. To establish the connection with the database, I have integrated node-odbc. To ensure tha ...

Preserve the newline character within a string in JavaScript

One of my API methods returns an RSA key in the following format: "publickey" : "-----BEGIN PUBLIC KEY-----\nMIGfMA0G CSqGSIb3DQEBAQUAA4GNADCBiQKBgQC5WleAVeW5gySd QVFkTi44q1cE\ncWDT2gmcv2mHcWhwI/9YqGV2LqpMASe 4t4XS/88fvTTHafHn1KaL9F7d73T9k4cp&bs ...

Primary tag badge using Bootstrap design

I am currently following a React tutorial by Mosh, where he is using the badge badge-primary class in a span tag. import React, { Component } from "react"; class Counter extends Component { state = { count: 0, }; render() { return ...