【问题标题】:Javascript find index of missing elements of two arraysJavascript查找两个数组的缺失元素的索引
【发布时间】:2019-03-07 21:48:54
【问题描述】:

我有以下 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) 之间缺失元素的索引吗?

【问题讨论】:

标签: javascript jquery arrays


【解决方案1】:

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

所以知道我们可以使用!array.includes(value) 来查看数组是否不包含值。我们现在必须遍历一个数组以获取条目并与另一个数组比较不在另一个数组中的项目。我们将为此使用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] 的数组。

// 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
    ]
*/

【讨论】:

  • 我也有这样的解决方案,但是 2 包含在两个数组中。我只想找到数组 1 中但不包含在数组 2 中的那些索引,例如: [1,2,3,4,5] 和 [2,1,5,4] 应该给出缺失的 3 和因此我想在第一个数组中获得 3 的索引
  • 对不起,我一开始很困惑。我修好了,我现在就知道了,第三次编辑哈哈。
【解决方案2】:

假设您在数组A 中有唯一元素,并且在数组B 中只出现一次。我们可以只使用 set 来添加数组 A 的所有元素,并在迭代数组 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 数组包含索引和元素所在的数组。

【讨论】:

    【解决方案3】:

    如果你有lodash的访问权限,你可以使用_.difference一行来解决这个问题。

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

    【讨论】:

    • 你有多维数组的样本吗?假设每个数组对象都包含 id 和 value 属性。
    【解决方案4】:

    从您的代码中可以看出,您需要比较两个对象的 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 中删除缺失的元素

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-12
      • 2017-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-09
      相关资源
      最近更新 更多