简体   繁体   中英

JS: Array print the values that repeat

I need to print the duplicates from an array.

For example, given the following array and index, the function will print 6,23,33,100 .

var array = [3,6,67,6,23,11,100,8,93,0,17,24,7,1,33,45,28,33,23,12,99,100];

Apparently we need to do it using two 'while loops'.

Im looking for a solution, but more importantly an explanation. Links are very much appreciated.

Thanks!

The most elegant and efficient solution is to use a while loop which iterates the array only once, so, we have O(N) complexity.

For this, we need to declare an hash which keeps the number of occurencies for each array's item . If we found a duplicate one then we store it in duplicates array.

 var arr = [3,6,67,6,23,11,100,8,93,0,17,24,7,1,33,45,28,33,23,12,99,100], i = 0, hash = {}, duplicates = []; while(i < arr.length){ hash[arr[i]] = hash[arr[i]] ? hash[arr[i]] += 1 : 1; if (hash[arr[i]] === 2) duplicates.push(arr[i]) i++; } console.log(duplicates)

You could use the filter() and indexOf() methods.

 var array = [3,6,67,6,23,11,100,8,93,0,17,24,7,1,33,45,28,33,23,12,99,100]; console.log(array.filter((a,b,c) => c.indexOf(a) !== b));

a -> is the value being passed in the arrow function.

b -> is the index being passed in.

c -> is the whole array being passed in.

This line is filtering the array based on, if the original array has a value (argument a) whose index does not match the given index passed in through the arrow function (argument b).

A good sample and explanation can be found here... W3Resource

Futhermore to assist in understanding the two major components of the code the Object... Working with objects - Javascipt

and Arrays... Javascipt Arrays

For the shortest approach, you could take a closure

(s =>                           )(       )

with a Set

(s =>                           )(new Set)

and a check. If a value is already seen, then take this value

(s => v => s.has(v)             )(new Set)

or add the value to the set and return false , because a not seen value should not in the result set.

(s => v =>             !s.add(v))(new Set)

 var array = [3, 6, 67, 6, 23, 11, 100, 8, 93, 0, 17, 24, 7, 1, 33, 45, 28, 33, 23, 12, 99, 100], duplicates = array.filter((s => v => s.has(v) || !s.add(v))(new Set)); console.log(duplicates);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM