GAS-从阵列中删除重复项的问题 [英] GAS - Issue with Removing Duplicates from Array

查看:70
本文介绍了GAS-从阵列中删除重复项的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一列包含一组我正在准备查询的数字.其中一些数字带有前导零,我需要将其保持在有前导零而没有前导零的列表中.

I have a column with a set of numbers I am prepping for a query. Some of these numbers have leading zeros and I will need to keep it on the list with leading zeros and without leading zeros.

到目前为止,我所做的是创建一列带前导和不带前导零的值.这是当我在列上getValues时的数组示例.

What I have done so far is to create a column of values with leading and without leading zeros. Here is an example of the array when I getValues on the column.

[[1],[2],[001],[002],[1],[2]]

最终结果应该是... [[1],[2],[001],[002]]

The end result should be... [[1],[2],[001],[002]]

最后两个被删除是因为它们是重复的,我只需要在数组中使用一次.

The last two were dropped because they were duplicates and I only need it in the array once.

这是我正在尝试的方法,但是我遇到了问题:

Here is what I am trying but I am having issues:

var array = sh.getRange(1,sh.getLastColumn(),sh.getLastRow(),1).getValues();
var uniqueArray = removeDuplicates(array)

function removeDuplicates(myArray){
  var newArray = [];
  myArray.forEach(function(x){
    if(newArray.indexOf(x[0]) === -1){
      newArray.push(x[0]);
    }                   
  });
}

错误:数组返回为null,然后当我尝试获取uniqueArray.length时,它会给我TypeError: Cannot read property 'length' of undefined

Error: The array comes back as null and then when I try to get uniqueArray.length it will give me TypeError: Cannot read property 'length' of undefined

我也尝试过:

var uniqueArray = Array.from(new Set(array));

这似乎会减少负担,我喜欢它,但是它返回所有值.它不会删除重复项.

This seems like it would be less taxing and I like it but it returns all values. It doesn't drop the duplicates.

我做错了什么,最好的方法是什么?我该如何解决?

What am I doing wrong and what is the best approach? How can I fix this?

推荐答案

使用集合:

const removeDuplicates = arr2d => [...new Set(arr2d.flat())].map(e => [e]);
console.info(removeDuplicates([[1],[2],[001],[002],[1],[2]]))

使用getDisplayValues获取字符串

这篇关于GAS-从阵列中删除重复项的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆