仅在保持正确序列的同时,将数组转换为唯一值

时间:2021-11-03 21:38:25

I have the following code:

我有以下代码:

function uniteUnique(arr) {
  //Create a single Array of value  
  arr = arguments[0].concat(arguments[1], arguments[2]);
  //Reduce the Array to unique values only
  arr = arr.reduce((pre, curr) => {
    //Some function to reduce values
  });
  return arr;
}

uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);

The goal is to produce a single Array containing only unique values while maintaining the order.

目标是在保持顺序的同时生成一个只包含唯一值的数组。

Currently it returns:

目前它返回:

[1, 3, 2, 5, 2, 1, 4, 2, 1]

I'm wanting to reduce this to:

我想把它简化为:

[1, 3, 2, 5, 4]

2 个解决方案

#1


4  

You can use Set for that:

你可以使用Set:

function uniteUnique(...args) {
    return [...new Set([].concat(...args))];
}
var u = uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);
console.log(u);

It maintains insertion order, and by nature only contains unique values.

它维护插入顺序,而本质上只包含惟一的值。

In ES5 you could do it by maintaining the used values as properties of a temporary object, while building the result array:

在ES5中,可以将使用的值作为临时对象的属性来维护,同时构建结果数组:

function uniteUnique(/* args */) {
    return [].concat.apply([], arguments).reduce(function (acc, v) {
        if (!acc[0][v]) acc[0][v] = acc[1].push(v); // assigns new length, i.e. > 0
        return acc;
    }, [ Object.create(null), [] ])[1];
}
var u = uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);
console.log(u);

#2


1  

You can use the Set object since it already keeps your values unique in one object:

您可以使用Set对象,因为它已经在一个对象中保持了您的值的惟一性:

const mySet = new Set([1, 3, 2, 5, 2, 1, 4, 2, 1]);
// returns:   Set { 1, 3, 4, 5 };

const arrayUniques = [...mySet];

console.log(arrayUniques); 
// returns:  [1, 3, 4, 5];

#1


4  

You can use Set for that:

你可以使用Set:

function uniteUnique(...args) {
    return [...new Set([].concat(...args))];
}
var u = uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);
console.log(u);

It maintains insertion order, and by nature only contains unique values.

它维护插入顺序,而本质上只包含惟一的值。

In ES5 you could do it by maintaining the used values as properties of a temporary object, while building the result array:

在ES5中,可以将使用的值作为临时对象的属性来维护,同时构建结果数组:

function uniteUnique(/* args */) {
    return [].concat.apply([], arguments).reduce(function (acc, v) {
        if (!acc[0][v]) acc[0][v] = acc[1].push(v); // assigns new length, i.e. > 0
        return acc;
    }, [ Object.create(null), [] ])[1];
}
var u = uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);
console.log(u);

#2


1  

You can use the Set object since it already keeps your values unique in one object:

您可以使用Set对象,因为它已经在一个对象中保持了您的值的惟一性:

const mySet = new Set([1, 3, 2, 5, 2, 1, 4, 2, 1]);
// returns:   Set { 1, 3, 4, 5 };

const arrayUniques = [...mySet];

console.log(arrayUniques); 
// returns:  [1, 3, 4, 5];