一旦我在数组上使用array.prototype.map/filter,是否可以将其转换回原始数组?

时间:2017-06-21 16:10:47

标签: javascript arrays

我正在研究FreeCodeCamp算法,要求我执行以下操作:

从数组中删除所有虚假值。

JavaScript中的虚假值为false,null,0,“”,undefined和NaN。

function bouncer(arr) {
  // First thing I did was change the arr argument into an array that changed all the values into true or false.
  var newArr = arr.map(function(elements) {
    return Boolean(elements);
  });
  // Now that all the elements are easily filterable, I did that exactly.

  var filterArr = newArr.filter(function(value) {
    return value === true;
    /*Freecodecamp keeps telling me to use '==' here instead of '==='. I know the difference between 
    the strict equality operator and the equality operator, but wouldn't '==' work just as well? 
    */ 
  });
  /* Now filterArr outputs [true, true, true]. 

     Is there anyway to somehow reverse the map method I used earlier
     so that it 'converts' the [true, true, true] array into [7, "ate", 9] as the output?
  */
  return filterArr;
}

bouncer([7, "ate", "", false, 9]);

因此,虽然我设法删除了虚假值,但我不知道如何将已过滤的数组分别转换回原始数组。我想自己解决这个问题,但我有点卡住了。

如果还有其他方法我应该使用?

如果代码看起来像废话,请道歉。我尝试用评论来解释我的思路和问题。

3 个答案:

答案 0 :(得分:1)

我认为这很容易,对吧?

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

console.log(bouncer([7, "ate", "", false, 9, 0, NaN, true, Infinity, null, undefined, {}]));

答案 1 :(得分:1)

只需过滤您已获得的数组,依赖于.filter将回调结果作为布尔值的事实:

function bouncer(arr) {
    return arr.filter(function(value) {
        return value;
    });
}

或ES6语法:

let bouncer = (arr) => arr.filter(v => v);

答案 2 :(得分:0)

由于已经提出了建议使用filter()的好答案,我将提供一个解决方案,以便在您真正想要修改原始阵列时,这是不寻常的,最好避免但具有有效的用例尽管如此:

function bouncer(arr) {
  var i = 0;
  while (i < arr.length) {
    if (arr[i]) {
      i++;
    } else {
      arr.splice(i, 1);
    }
  }
}