在数字数组中删除重复的数字

时间:2019-06-05 12:32:41

标签: javascript arrays

我需要一个将特定数字修整为数字数组中仅1个重复的函数。

我只能使用.pop.push .length命令。

如果我有数组,即[ 5,4,6,6,8,4,6,6,3,3,6,5,4,8,6,6],则需要修剪数字6的重复项以使其仅显示一次,因此结果将是-

[5,4,6,8,4,6,3,3,6,5,4,8,6].

仅使用一个数组。

我已经尝试过使用for循环遍历数组,并且如果我发现在另一个6之后出现的6,那么我每次找到重复的6时都会尝试将所有其他元素后退一步,{{1} }

我尝试在for循环中循环,没有运气。

3 个答案:

答案 0 :(得分:0)

在您的情况下,使用for循环迭代数组,如果当前项不是 要重复数据删除的项目,或与前一个项目不相同的项目,请将该项目添加到当前的counter中,然后递增counter。循环结束后,将数组的长度更改为计数器的长度。

function removeSpecificDuplicate(arr, item) {
  let counter = 0;

  for(let i = 0; i < arr.length; i++) {
    if(arr[i] !== item || arr[i] !== arr[i-1]) arr[counter++] = arr[i];
  }

  arr.length = counter;
}

const arr = [5,4,6,6,8,4,6,6,3,3,6,5,4,8,6,6]

removeSpecificDuplicate(arr, 6);

console.log(arr)

答案 1 :(得分:0)

通过关注当前值和下一个值是否实际上相同并且下一个值是目标值,可以循环数组并在适当位置重新分配值。 除此之外,还需要处理是否在数组末尾。

更多说明可以直接在下面的代码段中找到。

最后一点,期望的输出应该是:

[5,4,6,8,4,6,3,3,6,5,4,8,6]

代替

[5,4,6,8,4,6,3,3,6,5,3,8,6]

由于输入中最后一个8之前,所以您有4,而不是3。

function trimSpecificNumber(arr, target) {
  // Define a tracker that will update the array in-place.
  var _track = 0;
  // Loop over all the elements in the array.
  for (var i = 0; i < arr.length; i++) {
    // acquire the current and the next value.
    var _curr = arr[i], _next = arr[i+1];
    // If there is no next value, assign the last element of the array.
    if (!_next) arr[_track++] = _curr;
    else {
      // Otherwise, if the current element is not the same of the next one AND the next one actually isn't the searched needle, assign the current index to the current value (in place).
      if (_next === _curr && _next === target) {
         // Silence is golden, skip this one.
      }
      else {
        arr[_track++] = _curr;
      }
    }

  }
  // Finally, assign the new length of the array, so that next elements will be truncated.
  arr.length = _track;
}

var needle = [5,4,6,6,8,4,6,6,3,3,6,5,4,8,6,6];
trimSpecificNumber(needle, 6);
console.log(needle);

答案 2 :(得分:-1)

您可以执行以下操作:

const data = [ 5,4,6,6,8,4,6,6,3,3,6,5,4,8,6,6];
const ans = [];

data.forEach((x) => {	
       ans.push(x);  
       if (ans[ans.length - 1] === 6 && ans[ans.length - 2] === 6){
          ans.pop(x);    
       }  
});

console.log(ans);