2017-02-20 77 views
1

我正尝试在JavaScript中删除数组中的重复项。给定的数组是在JavaScript中删除数组中的重复项

array = [1,1,1,1,1,1,1,1,1,,1,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,1,1,1,1,1,2,2,2,2,2,2,2,2]

resultant_array = [1,2,3,1,2]

这里第二个1不被认为是一个重复的

OR

array = [1,1,1,1,1,1,1,1,1,1,1,1]

resultant_array = [1]

任何想法如何,我可以做到这一点

+0

[Lodash'uniq'](https://lodash.com/docs/#uniq)? – tadman

+0

你想做什么?删除重复项当且仅当它们是连续的? “22”发生了什么?你试过什么了? –

+0

所以你想删除连续的重复? replace(/((?:^ |,)([^,] +))(,\ 2(?=,| $))+/g,“$ 1” ).split(“,”);' –

回答

1

您可以使用reduce这样的:

var array = [1,1,1,1,1,1,1,1,1,,1,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,1,1,1,1,1,2,2,2,2,2,2,22]; 
 

 
var result = array.reduce(function(r, e) { 
 
    if(r[r.length - 1] != e) // if the last element in the result is not equal to this item, then push it (note: if r is empty then r[-1] will be undefined so the item will be pushed as any number is != undefined) 
 
    r.push(e); 
 
    return r; 
 
}, []); 
 

 
console.log(result);

1
var arr = [1,1,2,2,3,3]; 
var obj = {}; 
for(var i in arr) { 
    obj[arr[i]] = true; 
} 
var result = []; 
for(var i in obj) { 
    result.push(i); 
} 

我设置对象的键作为阵列的价值和不能有多个具有相同值的键。然后我把所有的钥匙放在结果中。

+0

这将在所有情况下给我[1,2,3] ...即使我通过[1,1,2,2,3,3,1,1,2,2,3,3]。在这种情况下,我需要[1,2,3,1,2,3] – Mahima

+0

这可能没有回答OP的问题,但它确实回答了我的问题。谢谢! –

1

你可以检查的前身与Array#reduce

var array = [1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2], 
 
    result = array.reduce(function (r, a) { 
 
     return r[r.length - 1] === a ? r : r.concat(a); 
 
    }, []); 
 
    
 
console.log(result);

或使用Array#filter和最后一个值的对象。

var array = [1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2], 
 
    result = array.filter(function (a, i, aa) { 
 
     return this.last !== a && (this.last = a, true); 
 
    }, { last: undefined }); 
 
    
 
console.log(result);

+0

谢谢。那22是一个错字。我纠正了它。你能告诉我这是如何工作的吗? – Mahima

+0

'concat'似乎有点消耗资源,因为它每次都会创建一个新的数组! –

+0

@ibrahimmahrir,你可以使用过滤器... –