如何比较两个数组并提醒结果?

时间:2017-12-07 04:11:01

标签: javascript jquery arrays

我有两个简单的数组:

var arr_must_exist = ["1","2","3"];
var arr_created    = ["2","4","7","8"]; //This is varies depend of the array created.

因此,如果arr_created与示例类似,则应该有Your choice must contain 1 and 3

之类的提醒

示例:

arr_created    = ["2","4","7","8"];
alert(`Your choice must contain 1 and 3`)

arr_created    = ["2","3","7","8"];
alert(`Your choice must contain 1`)

arr_created    = ["4","5","7","8"];
alert(`Your choice must contain 1, 2 and 3`)

arr_created    = ["1","2","9","3"];
alert(`Your choice is valid`)

我使用$.each,但它只检查数组。不比较它们。

$.each(arr_is_must_exist , function(index, val_must_exist) { 

        $.each(arr_is_exist_in_table , function(index, val_is_exist) { 
            if(val_must_exist != val_is_exist){
              alert("Your choice must contain 1,2,3");
            }
        });
});

我看here但是没有接受答案。我使用IE和Mozilla(它是本地用户的)

6 个答案:

答案 0 :(得分:9)

您可以找到如下所示的缺失项目数组:

var arr_must_exist = ["1","2","3"];
var arr_created    = ["2","4","7","8"];
var missing = arr_must_exist.filter(e => arr_created.indexOf(e) < 0);

console.log(missing);

答案 1 :(得分:2)

您可以通过简单的javascript和日志消息来完成

var arr_must_exist = ["1","2","3"];
var arr_created    = ["2","4","7","8"]; 
//This is varies depend of the array created.

var numberNotAvailable = [];

for(var i = 0; i<arr_must_exist.length; i++){
  console.log(arr_created.indexOf(arr_must_exist[i]));
  if(arr_created.indexOf(arr_must_exist[i]) < 0){
        console.log(arr_must_exist[i] + ' added');    
        numberNotAvailable.push(arr_must_exist[i])
  }  
}

var logMessage ;
if(numberNotAvailable.length == 0){
  logMessage = 'Your choice is valid';
}
else if(numberNotAvailable.length == 1){
  logMessage = 'Your choice must contain ' + numberNotAvailable[0];  
}
else if(numberNotAvailable.length == 2){
  logMessage = 'Your choice must contain ' + numberNotAvailable[0] + ' and ' + numberNotAvailable[1];  
}
else if(numberNotAvailable.length > 2){  
  logMessage = 'Your choice must contain ' + fruits.join();  
}

console.log(logMessage);

答案 2 :(得分:1)

可以使用forEach&amp; amp;连接数组方法

&#13;
&#13;
var arr_must_exist = ["1", "2", "3"];
var arr_created = ["2", "4", "7", "8"];
  
// An array to store the elements which are not in arr_created
var missingElements = [];

// looping over arr_must_exist and checking if 
// element is present in arr_created using indexOf
arr_must_exist.forEach(function(item) {
  if (arr_created.indexOf(item) === -1) {
    // if not push the element in the array
    missingElements.push(item)

  }
})
   
// if missingElements length is greater than 1 mean if it contain 
// any element then join all the element ,create string with a comma 
//separator
if (missingElements.length > 0) {
  alert(missingElements.join(','))
}
&#13;
&#13;
&#13;

答案 3 :(得分:0)

您必须编写一个执行比较的函数并将差异存储在数组中

var arr_must_exist = ["1","2","3"];
var arr_created    = ["2","4","7","8"];
var diff = [];
arr_must_exist.forEach(function(value){
   if(arr_created.indexOf(value) < 0) {
     diff.push(value);
    } 
});
var str = '';
if(diff.length) {
    var str = 'Your choice must contain ';
    diff.forEach(function(value, index) {
        str += ((index+1 == diff.length) ? ' and ' + value : value)
    });
} else {
    str = 'Your choice is valid';
}
alert(str);

答案 4 :(得分:0)

使用Set检查arr_must_exist中每个项目是否存在。

它还使用正则表达式来获取"and"","权限,并使用模板文字将消息放在一起。

const arr_must_exist = ["1","2","3"];

function getMsg(arr_created) {
  const set = new Set(arr_created);
  const m = arr_must_exist.filter(s => !set.has(s))
                          .join(", ")
                          .replace(/, ([^,]+)$/, " and $1");

  return `Your choice ${m ? "must contain " + m : "is valid"}`;
}

console.log(getMsg(["2","4","7","8"]));
console.log(getMsg(["2","3","7","8"]));
console.log(getMsg(["4","5","7","8"]));
console.log(getMsg(["1","2","9","3"]));

答案 5 :(得分:0)

有各种方法可以使用有限数量的练习。 喜欢

  1. 通过$ .map()函数
  2. 按$ .filter()函数
  3. 通过数组与循环的多个比较
  4.   

    代码示例:

    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
    <script>
    var arr_must_exist = ["1","2","3"];
    var arr_created    = ["2","4","7","8"];
    var noElement =[];
    // This Example contains the `$.map()` function to accomplish the task.
    $.map(arr_must_exist, function(el){
      if($.inArray(el, arr_created) < 0)
      {
            noElement.push(el);
           return null;
      }
      else
      {
          return el;
      } 
      return $.inArray(el, arr_created) < 0 ? null : el;
    });
    if(noElement.length <= 0)
    {
    console.log("Your choice is valid");
    }
    else
    {
    console.log("Your choice must contain "+noElement);
    }
    
    //This example contain the `$.filter()` check;
    
    $checkarray = arr_must_exist.filter(e => arr_created.indexOf(e) < 0);
    
    
     if($checkarray.length == 0)
     {
        console.log("Your choice is valid");
     }
     else
     {
        console.log("Your choice must contain "+ $checkarray);
     }
    </script>