从阵列中删除所有某些重复项

时间:2019-06-21 09:23:38

标签: javascript arrays

我有两个不同的数组,我想删除第二个数组中存在的第一个数组元素的所有副本。我已经尝试了一些splice和indexOf方法,但未能实现。检查了其他一些帖子,但找不到我正在寻找的东西。这是下面的示例代码。谢谢大家。

let container = [1, 2, 2, 2, 3, 3, 3, 4, 5];
let removing = [2, 3];


function func(container, removing){
  let result = //i want to write a function there which will remove all duplicates of "removing" from "container".
  return result; // result = [1, 4, 5]
}

5 个答案:

答案 0 :(得分:9)

你在这里

STM32L072xx,USE_B_<board name>,USE_HAL_DRIVER,REGION_EU868,DEBUG,TRACE

如果出于某种原因您担心这样做的效率,可以将线性let container = [1, 2, 2, 2, 3, 3, 3, 4, 5]; let removing = [2, 3]; let difference = (a, b) => a.filter(x => !b.includes(x)); console.log(difference(container, removing))检查替换为includes集合查找:

O(1)

答案 1 :(得分:1)

filterincludes一起使用:

let container = [1, 2, 2, 2, 3, 3, 3, 4, 5];
let removing = [2, 3];


function func(container, removing){
  let result = container.filter(e => !removing.includes(e));
  return result;
}

console.log(func(container, removing));

ES5语法:

var container = [1, 2, 2, 2, 3, 3, 3, 4, 5];
var removing = [2, 3];


function func(container, removing){
  var result = container.filter(function(e) {
    return removing.indexOf(e) == -1;
  });
  return result;
}

console.log(func(container, removing));

答案 2 :(得分:1)

您可以这样做,

query = 'SELECT * FROM abc'
if len(params) > 0:
    filters = ["{}=%s".format(k) for k in params]

    print(filters)
    #query += " WHERE " + " and ".join(filters)
    #and="and"
    query += " WHERE " + "and"  .join(filters) 
    print(query)
    #t = tuple(params.values())
    t = tuple(params.values())

    print(t)
    print(type(t))
    conn = pyodbc.connect('Driver={SQL Server};'
                  'Server=DESKTOP;'
                  'Database=xyz;'
                  'Trusted_Connection=yes;')

    c = conn.cursor()
    c.executemany(query, t)
    return c.fetchall()

答案 3 :(得分:0)

这可以做到:

function func(container, removing){
    let result = container.filter(x => !removing.includes(x));
    return result;
}

答案 4 :(得分:0)

尝试一下:

let container = [1, 2, 2, 2, 3, 3, 3, 4, 5];
let removing = [2, 3];


const func = (container, removing) => container.filter(res=>!removing.includes(res));
  
console.log(func(container,removing));