1

I am working on some code that takes an array of numbers and will remove any blanks and numbers with commas in them from the array.

for(var x = 0; z<employeeIDs.length; x++){
    if(employeeIDs[x] == ""){
        employeeIDs.splice(x, 1)
        x--
        continue
    }
    if(employeeIDs.includes(",")){
        employeeIDs.splice(x, 1)
        x--
    }
}

it seems to be working for the blanks but not the commas... Anyone see why that may be the case?

UPDATE:

I created another identical for loop and moved the 2nd if statement to that loop and things work as intended. I still don't know why it wouldn't work under the same loop?

3
  • Looks like a lot of work for something Array.filter was designed to help with Commented Jun 21, 2021 at 17:43
  • The second condition should be employeeIDs[x].includes(","), not employeeIDs.includes(","). And in for loop you have z instead of x Commented Jun 21, 2021 at 18:02
  • @adiga :O the z was a typo but that [x] was what I was missing! Sometimes all it takes is a 2nd set of eyes. Thanks! Commented Jun 21, 2021 at 18:06

1 Answer 1

2

Your code is not working because you are not checking if the item at index x includes(",").

const employeeIDs = ["544545", "5454", "", "54,5487"];

for(var x = 0; x <employeeIDs.length; x++){
    if(employeeIDs[x] == ""){
        employeeIDs.splice(x, 1)
        x--
    }
    if(employeeIDs[x].includes(",")){ // check for [x]
        employeeIDs.splice(x, 1)
        x--
    }
}

console.log(employeeIDs);

Another way you could accomplish this is by using the filter array method. Return the values that result as truthy (no empty values), and values that don't include ,.

const employeeIDs = ["544545", "5454", "", "54,5487"];

const result = employeeIDs.filter((id) => id && !id.includes(","));

console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.