通过非数组第二个参数过滤第一个参数数组

时间:2015-03-01 20:30:33

标签: javascript arrays

我是一名javascript初学者,试图解决在线代码阵营带来的挑战。此问题类似于Using an array to filter an array Javascript提出的问题。我研究了这个,但仍未成功。我已经尝试了很多个小时而没有找到解决方案。

具体挑战是:

  

从数组中移除所有值(最后一个参数)(第一个参数)和>作为新数组返回。

我知道这并不多。在下面的示例中,所需的输出将是以下数组:

  

[1,1]

基本前提是通过x个非数组参数过滤第一个参数,即一个数组。在数组元素与非数组参数相同的情况下,这些元素将从数组中删除。以下是我尝试过的路径的无效功能样本:

<code>
     function result(arr) {
  var list = [];
  var i;
  for(i in Object.keys(arguments)) {
      if(i > 0) {
          list.push(arguments[i]);
      }
  }

  function answer(arr1, arr2) {
    return arr1.filter(function(a) {
        return arr2.indexOf(a) >= 0;
    });
  }

  return answer(arr, list);
}
result([1, 2, 3, 1, 2, 3], 2, 3); 
</code>

3 个答案:

答案 0 :(得分:0)

好的,现在也许我明白了。如果这是实际的挑战措辞,那么措辞很差。

我的解释是,你被要求编写一个函数,它接受一个数组的第一个参数,然后是零个或多个连续参数。任务是从传入的数组中删除所有零个或多个连续的参数,并返回一个删除了这些项的新数组。

function filterArray(sourceArray, arg1, arg2 /* ... more args */) {
    // get arguments after the first argument into their own array
    var args = Array.prototype.slice.call(arguments, 1);
    return sourceArray.filter(function(element, index, array) {
        return args.indexOf(element) === -1;
    });
}

这可以通过将连续的参数放入他们自己的数组然后在.filter()上调用sourceArray来实现。然后.filter()的回调使用.indexOf()来检查每个元素是否在参数列表中。如果不是,请返回true以保留输出数组中的值。如果它在参数列表中,则返回false,以便从输出数组中删除它。

工作演示:http://jsfiddle.net/jfriend00/u8c5vvd9/


如果您希望在IE9之前与IE版本兼容,您可以添加.filter().indexOf()的polyfill,这很容易显示herehere或者您可以像这样手动进行过滤:

function filterArray(sourceArray, arg1, arg2 /* ... more args */) {
    var result = [], found, item;
    for (var i = 0; i < sourceArray.length; i++) {
        item = sourceArray[i];
        found = false;
        for (var argIndex = 1; argIndex < arguments.length; argIndex++) {
            if (arguments[argIndex] === item) {
                found = true;
                break;
            }
        }
        if (!found) {
            result.push(item);
        }
    }
    return result;
}

工作演示:http://jsfiddle.net/jfriend00/g586cbpp/

答案 1 :(得分:0)

我能想象的最简单的解决方案是:

function result(haystack) {
    // converting the 'non-array' list of additional arguments
    // into an array:
    var needles = Array.prototype.slice.call(arguments, 1),
        // using Array.prototype.filter() to filter the 
        // supplied array ('haystack'):
        filtered = haystack.filter(function (el) {
            // the first argument ('el') is the current array-element

            // if the current array-element is *not* found in the
            // array of 'needles', we retain the element:
            return needles.indexOf(el) === -1;
        });
    return filtered;
}

console.log(result([1, 2, 3, 1, 2, 3], 2, 3)); // [1, 1]

此解决方案,尤其是Array.prototype.filter()的使用,在IE 8中存在问题,MDN参考链接(下方)为那些旧浏览器提供了垫片。

function result(haystack) {
  var needles = Array.prototype.slice.call(arguments, 1),
    filtered = haystack.filter(function(el) {
      return needles.indexOf(el) === -1;
    });
  
  /* just to display the values: */
  document.getElementById('haystack').textContent = haystack.join(', ');
  document.getElementById('needles').textContent = needles.join(', ');
  document.getElementById('result').textContent = filtered.join(', ');
  
  return filtered;
}

console.log(result([1, 2, 3, 1, 2, 3], 2, 3));
ol, li {
  list-style-type: none;
}

li::before {
  content: attr(id) ': ';
  display: inline-block;
  width: 20%;
  text-transform: capitalize;
}

li:empty {
  display: none;
}
<ol>
  <li id="haystack"></li>
  <li id="needles"></li>
  <li id="result"></li>
  </ol>

参考文献:

答案 2 :(得分:0)

这将检查所有参数与输入数组中的值的完全匹配。然后返回一个剥去这些值的数组。

它不会使用.filter() .slice() .call()Object.keys(),因此它完全符合古老的网络浏览器版本。

<script type="text/javascript">

function result(input_array) {
    //  Breakpoint if input is not an array... return the object inside an array for consistency of return type
    if( !(input_array instanceof Array) ) return [].push(input_array);

    //  Gather list of arguments to reject.
    var reject_list = [];
    for(var i in arguments)
        if(i > 0)
            reject_list.push(arguments[i]);

    //  check each element in the input array if it is a value to reject.
    var output_array = []
    for(var i = 0; i < input_array.length; i++){
        var value_is_ok = true
        for(var r = 0; r < reject_list.length; r++){
            if( input_array[i] == reject_list[r] ){
                value_is_ok = false
                break
            }//endif
        }//endfor

        if( value_is_ok )
            output_array.push(input_array[i]);

    }//endfor


    return output_array
}

var my_array = [1, 2, 3, 1, 2, 3]
console.log( result(my_array, 2, 3) )   //  result is [1,1]

</script>