myLogicIsWrong
myLogicIsWrong

Reputation: 67

Replace digit in number if exists or push to end if it doesn't exist

Given the following data:

var x = 3
var number = 0621

How can I enumerate through number and try to find x digit in that number? If x exists in number, remove that number.

Can a integer be treated as an array?

Upvotes: 1

Views: 150

Answers (3)

Álvaro Touzón
Álvaro Touzón

Reputation: 1230

Would be some like this?

var x = 3
var number = 0621;
var _new = '';
for (var t = 0; t < String(number).length; t++) {
  if (String(number).charAt(t) !== String(x)) _new += String(number).charAt(t);
}

console.log('and new', +_new);

Upvotes: 0

cнŝdk
cнŝdk

Reputation: 32145

Can a integer be treated as an array?

You can cast your number as a string then split it, this will give you an array.

How can I enumerate through number and try to find x digit in that number? If x exists in number, remove that number

Now you can loop over the digits array to check if your inputted x is among them.

This is what you need:

var x = 3
var number = 5783;
//This will give you an array with your digits
var arr = (String(number)).split('');

if (arr.indexOf(String(x)) === -1) {
  arr.push(x);
} else {
  arr = arr.map(function(n) {
    return n == x ? '' : n;
  });
}

console.log(arr.join(''));

Note:

Note that leading 0 in a number will give you unexpected resluts, so be careful about that.

Upvotes: 0

mplungjan
mplungjan

Reputation: 178160

Be careful. Number will be 401 as soon as you have assigned 0621 to it because of octal issues - extra tricky with the invalid octal numbers 08 and 09.

Instead make number a string and you can use charAt or indexOf:

function chop(numString,num) {
  var pos = numString.indexOf(""+num); 
  if (pos ==-1) numString+=num; 
  else numString = numString.slice(0, pos) + numString.slice(pos+1);
  return numString;
}

var num = 0621;
console.log("Octal",num); // to show the octal issue

// better: 
console.log(chop("0621", 2));
console.log(chop("0621", 3));

Upvotes: 2

Related Questions