vaacuum
vaacuum

Reputation: 15

Why the splice function doesn't work properly in JavaScript?

function scramble(str1, str2) {
    for (var i=0; i<str2.length; i++){
        if (str1.split('').indexOf(str2[i])>=0){
            str1.split('').splice(str1.split('').indexOf(str2[i]),1);
            console.log(str1)
        } else {return false};
    } return true
}

scramble('rkqodlw','world')

I have a question about the splice function, after running this code, the str1 doesn't change every time, and I really don't know where the problem is.

Upvotes: 0

Views: 90

Answers (4)

Maheer Ali
Maheer Ali

Reputation: 36574

Because you are not apply splice() on str1. You are applying splice() on str1.split(''). To fix this assign str1 to array in start of function and then use splice()

According to MDN

All types except objects define immutable values (values, which are incapable of being changed). For example and unlike to C, Strings are immutable. We refer to values of these types as primitive values.

str1.split('') doesnot change the value of str1 instead it return a new value which should stored in variable.

function scramble(str1, str2) {
    str1 = str1.split('');
    for (var i=0; i<str2.length; i++){
        if (str1.indexOf(str2[i])>=0){
            str1.splice(str1.indexOf(str2[i]),1);
            console.log(str1.join(''))
        } else {return false};
    } return true
}

scramble('rkqodlw','world')

Easier Way:

You can do that easier way using filter() and includes()

function scramble(str1, str2) {
     return str1.split('').filter(x => !str2.includes(x))
}
console.log(scramble('rkqodlw','world'))

Upvotes: 1

prasanth
prasanth

Reputation: 22500

You are return same str1 not with after spliced value.So you need to defined split before loop spl.

function scramble(str1, str2) {
  var spl =str1.split('');
  for (var i = 0; i < str2.length; i++) {
    if (spl.indexOf(str2[i]) > -1) {
      spl.splice(spl.indexOf(str2[i]), 1);
      console.log(spl.join(''))
    } else {
      return false
    };
  }
  return true
}

scramble('rkqodlw', 'world')

For simplified version

function scramble(str1, str2) {
  str2.split('').forEach(a=> str1=str1.replace(a,''));
  return str1;
}

console.log(scramble('rkqodlw', 'world'))

Upvotes: 0

junvar
junvar

Reputation: 11574

str1.split('') returns a new array. Calling splice on this array will modify that array and not str1.

Splice on an array will modify the array:

let arr = [1, 2, 3];
arr.splice(2);
arr;  // [1, 2]

But not the string the array was constructed from.

let str = '1 2 3';
let arr = str.split(' ');
arr.splice(2);
str; // ' 1 2 3'
arr; // ['1', '2']

Upvotes: 0

qunshan
qunshan

Reputation: 57

str1.split('') return new Array of string and str1 is NOT changed.

Upvotes: 1

Related Questions