繁体   English   中英

Javascript查找两个数组的缺失元素的索引

[英]Javascript find index of missing elements of two arrays

我有以下JavaScript,其中有一些列表:

var deleteLinks = $(".remove-button .remove-from-cart");
deleteLinks.on('click', function(ev){
    ev.preventDefault();
    console.log("registered: " + deleteLinks);
    var currentHTML = $('.product');
    var currentText = $('.product .product-details .name-header');  
    var newHTML ;
        $.ajax({
        url: this.href,
        type: "GET",
        dataType: "html",
          success: function(data) {
              newHTML = $(data).find('.product .product-details .name-header'); 
              for(i = 0; i  < newHTML.length; i++){
                  console.log("new: " + newHTML[i].innerText);
                  console.log("old: " + currentText[i].innerText);
              }
          }
    });
});

变量currentHTML包含一个作为容器的div数组。 currentText包含每个容器名称的数组。 AJAX响应( newHTML )中收到的变量包含一个名称数组。 某些用户交互后,此数组将更新。 currentText变量的一个或多个条目可能会丢失,我想找到它们的索引,以便将其从容器( currentHTML )中删除。

有人可以帮我找到currentText和检索到的数据( newHTML )之间缺少元素的索引吗?

为了比较两个数组的值,有许多不同的方法可以简单地查看一个值是否在另一个数组中。 您可以使用array.indexOf(value)返回元素在另一个数组中的位置,如果结果大于预期的-1 ,则表示存在该元素或相反。 您也可以使用array.includes(value) ,另一种方法是使用!array.includes(value)来简单查看是否不存在!array.includes(value)

因此,知道我们可以使用!array.includes(value)来查看数组是否不包含值。 现在,我们必须遍历一个数组以获取条目,并与另一个数组进行比较以查找不在另一个数组中的项目。 我们将array.forEach()使用array.forEach() 我们可以使用array.some()设计更多的递归函数,但是我只是想给你一些简单的例子。

范例1。

 // Data let a = [1, 2, 3, 4, 5]; // Array A let b = [1, 0, 9, 3, 5]; // Array B // Basic principals function check(a, b) { // Loop through A using array.some() => value a.forEach(value => { // B did not include value if (!b.includes(value)) { // Output console.log("B doesn't have", value, "at position", a.indexOf(value), "in A") } }); // Loop through B using array.some() => value b.forEach(value => { // A did not include value if (!a.includes(value)) { // Output console.log("A doesn't have", value, "at position", b.indexOf(value), "in B") } }); } // We are checking both Arrays A and B check([1, 2, 3, 4, 5], [1, 0, 9, 3, 5]); 

例子2

让我们为数组元素制作一个原型,然后针对数组B调用比较函数,而不仅仅是输出到控制台进行演示。 如果该值不在数组B中,但实际上在数组A中 [value, position]我们将返回一个带有[value, position]数组。

 // Data let a = [1, 2, 3, 4, 5]; // Array A let b = [1, 0, 9, 3, 5]; // Array B /* Check an array for non-duplicates against another array. If the value of item in array A is present in array B, return [false, -1]. If value of item in array A is not present in B, return value and position of value in array A. */ Array.prototype.check = function(b) { /* * return if true * [value, position] * else * [false, -1] * */ return a.map(v => { return (!b.includes(v) ? [v, a.indexOf(v)] : [false, -1]) }) }; // Array A is checking against array B console.log(a.check(b)); /* Output: (A checking against B) [ [ false, -1 ], // Array element 1 found in B [ 2, 1 ], // Array element 2 not found in B, and has position 1 in A [ false, -1 ], // Array element 3 found in B [ 4, 3 ], // Array element 4 not found in B, and has position 3 in A [ false, -1 ] // Array element 5 found in B ] */ 

假设您在数组A具有唯一元素,而在数组B只有一个元素。 我们可以使用set来添加数组A所有元素,并在遍历Array B时从集合中删除这些元素。 使用findIndex查找集合中剩余的元素。

const a = [1,2,3,4,5];
const b = [2,1,5,4];
let set = new Set();
a.forEach(ele => set.add(ele));
b.forEach(ele => {
  if(set.has(ele)){
    set.remove(ele);
  }
});
let res = [];
for(let s of set) {
  if(a.findIndex(s) !== -1) {
    res.push({
     arr:  a,
     pos: a.findeIndex(s)
    });
  }else {
    res.push({
     arr:  b,
     pos: b.findeIndex(s)
    });
  }
}

res数组包含索引和元素所在的数组。

如果可以访问lodash ,则可以使用_.difference一行解决此问题。

 var a = ['a', 'b', 'c'], b = ['b'], result = []; _.difference(a, b).forEach(function(t) {result.push(a.indexOf(t))}); console.log(result); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script> 

从您的代码中可以看到,您需要比较两个对象的innerText并找到丢失的元素的索引。

var missing_indices = [];
for(var i=0;i<currentText.length;i++){
    var found = false;
    for(var j=0;j<newHTML.length;j++){
        if(currentText[i].innerText == newHTML[j].innerText){
            found = true;
            break;
        }
    }
    if(!found){
        missing_indices.push(i);
    }
}

然后使用missing_indices从currentHTML中删除丢失的元素

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM