从初始数组中删除与初始数组后跟的参数值相同的所有元素

问题描述 投票:0回答:5

有一个初始数组(驱逐舰函数中的第一个参数),后跟一个或多个参数。从初始数组中删除与这些参数具有相同值的所有元素。

这是我的代码,但我无法解决问题。

function destroyer(arr) {
// First I have converted the whole input into an array including the arguments
var args = Array.prototype.slice.call(arguments);
var abc=args.splice(0,1);//Here I have taken out the array part i.e[1,2,3,1,2,3] and also now args contain 2,3 only

function des(abc){
           for(var i=0;i<abc.length;i++){//I tried to check it for whole length of abc array
                if(args.indexOf(abc)===-1){
   return true;   //This should return elements of [1,2,3,1,2,3] which are not equal to 2,3 i.e [1,1] but for string inputs it is working correctly.How to do for these numbers?
     }
  }
}
return arr.filter(des); //but this filter function is returning  empty.How to solve my problem??
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);

对于驱逐舰([“树”,“汉堡”,53],“树”,53)代码给出输出[“汉堡包”],这是正常的。

但对于驱逐舰([1,2,3,1,2,3],2,3);代码没有输出。

javascript arguments indexof destroy splice
5个回答
0
投票

试试这个:

function destroyer(arr) {
    var args = Array.prototype.slice.call(arguments, 1);

    function des(abc){
        return args.indexOf(abc) === -1;
    }
    return arr.filter(des);
}
var result = destroyer([1, 2, 3, 1, 2, 3], 2, 3);
document.getElementById('output').innerHTML = JSON.stringify(result);
<pre id="output"></pre>

1
投票

你可以使用Array.filter。下面的例子描述了相同的

destroyer([1, 2, 3, 1, 2, 3], 2, 3);也是[1, 2, 3, 1, 2, 3]的第一个参数,2排名第二,3排名第三。所以arr将是[1, 2, 3, 1, 2, 3]而不是[1, 2, 3, 1, 2, 3], 2, 3

function removeElementFromArray(arr,num){
  var _temp = arr.filter(function(item){
      return (item !== num);
  });
  
  return _temp;
}

(function main(){
  var arr = [1,1,1,2,4,3,2,4,5,4,3,1,4,5,2];
  var result = removeElementFromArray(arr,1);
  var result1 = removeElementFromArray(arr,3);
  
  console.log(result, result1);
})()

0
投票

Lodash没有可用的方法。

link to doc

来自lodash docs:

_.without(array,[values])

使用SameValueZero创建一个排除所有提供值的数组,以进行相等比较。

例:

_.without([1, 2, 1, 3], 1, 2);
// → [3]

0
投票

这应该适合你:

function destroyer(arr) {
    var args = Array.prototype.slice.call(arguments);
    var abc = args.splice(0, 1);
    function des(value) {
        // you don't need loop here, just check if given value is in args array
        return args.indexOf(value) === -1;
    }
    // splice returns array of deleted elements so that your first argument is abc[0]
    return abc[0].filter(des);
}
var result = destroyer([1, 2, 3, 1, 2, 3], 2, 3);
console.log(result);

0
投票

试试这个简单的代码:

function destroyer(arr) {
  /* Put all arguments in an array using spread operator and remove elements 
     starting from 1 */
  const args = [...arguments].splice(1);
  /* Check whether arguments include elements from an array and return all that 
     do not include(false) */
  return arr.filter(el => !args.includes(el));
}

destroyer([1, 2, 3, 1, 2, 3], 2, 3); // [1, 1]
© www.soinside.com 2019 - 2024. All rights reserved.