【问题标题】:Remove specific array from multiple array set using jquery使用 jquery 从多个数组集中删除特定数组
【发布时间】:2025-11-25 23:00:01
【问题描述】:

我有两个复选框。当我选中一个时,代码将获取该复选框的状态和 id 并推送到数组中,如果该值尚不存在

数组集合变成这样

  [8,0] [10,0]

要求:

  1. 如果我检查然后取消选中并再次检查它,它会插入 [8,0] [8,0] 两次,所以这不应该插入多次相同的值
  2. 从数组集中删除特定数组,因此如果我取消选中 chkecbox,则仅删除 [8,0] 但保留 [10,0]

var positions = [];

$("body").on('click', '.check_box', function() {
  var id = $(this).attr('data-id');
  var status = $(this).attr('data-status');
  if ($(this).prop("checked") == true) { // if click on check
    if (!$.inArray(id, positions)) positions.push(id); // if id and status not in array then only push
    positions.push([id, status]); //  it will  insert  like [8,10] but geting duplicate  [8,10] [8,10]
    console.log(positions);
  } else {
    // if uncheck checkbox

    //  remove specific  value like  [8,0] or if value present [10,0] then remove this
    console.log(positions);
  }

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="check_box" data-id="8" data-status="0">

<input type="checkbox" class="check_box" data-id="10" data-status="0">

【问题讨论】:

  • 你需要在删除数组中的值时检查索引,你可以使用splicehttps://www.w3schools.com/jsref/jsref_slice_array.asp
  • 我给你做了一个sn-p。
  • @jishansiddique 我也试过了,但它没有像 [8,0] 那样删除单个集合

标签: javascript jquery arrays push


【解决方案1】:

您可以使用indexOf 检查对象是否存在于数组中并仅在不存在时添加

对于删除,您可以使用filter 并仅选择数组中不完全符合您指定的对象

var positions = [];

$("body").on('click', '.check_box', function() {
  var id = $(this).attr('data-id');
  var status = $(this).attr('data-status');
  if ($(this).prop("checked") == true) {
    var exists = false;
    positions.forEach((p) => {
      if (id == p[0] && status == p[1]);
        exists = true;
    });
    if (!exists) {
      positions.push([id, status]);
    }  
  } else {
    positions = positions.filter(function(a) {
      return !(a[0] == id && a[1] == status);
    });
  }
  console.log(positions);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="check_box" data-id="8" data-status="0">

<input type="checkbox" class="check_box" data-id="10" data-status="0">

解释

  1. 在第一个循环 .each 中,我们遍历数组中的每个现有值,并在找到与我们选择的元素具有相同 id 和状态的元素时将 exist 设置为 true

    • 如果在循环之后我们已经存在为真,我们知道它已经存在并且我们不会将它推送到数组,否则我们会将它推送到数组
  2. 在 else 条件下,我们使用了数组的 filter 函数,此函数过滤数组并仅保留我们返回 true 的元素,对于返回 false 的元素,它将从结果数组中删除

    • 所以我们确实检查了数组的每个元素是否与 idstatus 完全匹配,如果匹配,我们返回 false,所以它会从结果数组中删除

【讨论】:

  • 一次又一次插入相同的值是不行的
  • 我想在选中时插入该值,如果我取消选中与复选框相关的复选框值应该被删除
  • @mplungjan 我试过 if(positions.indexOf([id,status])===-1) 但这也不能阻止推送重复值
  • 我刚刚更新了代码,请运行并再次检查
  • 非常感谢您节省了我的时间,我在过去一小时工作,请您解释一下循环概念和您的代码,只是一点点
【解决方案2】:

我会用findIndexsplice来处理,希望对你有帮助:)

$(function() {
    let positions = [];
    $("body").on('click', 'input:checkbox', function() {
        let id = $(this).attr('data-id');
        let status = $(this).attr('data-status');
        let data = [id, status];
        if ($(this).is(':checked')) {
            positions.push(data);
        } else {
            let index = positions.findIndex(c => c[0] === id);
            if (index != -1)
                positions.splice(index, 1);
        }
        $('#result').html(positions.toString());
    });
});
#result{
  width: 20rem;
  height: 1rem;
  margin-top: 2rem;
  border-width:3px;
  border-style:dashed;
  border-color:#FFAC55;
  padding: 15px 20px;
}
<!DOCTYPE html>
<html>

<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>

<body>
    <input type="checkbox" data-id="A" data-status="0">A</button>
    <input type="checkbox" data-id="B" data-status="0">B</button>
    <div id="result"></div>
</body>

</html>

【讨论】:

    【解决方案3】:

    如果数组很小,每次都重新创建一次

    let positions;
    $("body").on('click', '.check_box', function() {
      positions = [];
      $(".check_box:checked").each(function() {
        positions.push([
         $(this).data('id'), $(this).data('status')
       ]);
      });
      console.log(positions);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input type="checkbox" class="check_box" data-id="8" data-status="0">
    
    <input type="checkbox" class="check_box" data-id="10" data-status="0">

    【讨论】:

    • 感谢您的回答和宝贵的时间。我也会考虑这个