Unique Function

Unique Function to Remove Duplicate Integers in Array

by ramsunvtech

HTML

<p>
Check the console
</p>

JavaScript

'use strict';

	function unique (list) {
		// Return empty array if parameter is empty.
		if(!list) return [];

		// Check if list is an Array Object.
		if( list.constructor === Array) {
			var sortedList, uniqueList = [];

			// Sort the Array in Ascending Array.
			sortedList = list.sort( function (a, b) {
				return a-b;
			} );

			// Check if iterable.
			if(sortedList.length > 0)  {
				// Iterate the Array to remove duplicates.
				for(var i = 0; i < sortedList.length; i++) {
					// Make sure whether its integer.
					var n = parseInt( sortedList[i] );

					// Make sure type is same.
					// Note: indexOf will not work in IE8 so we can iterate and find for exist check.
					if( Number(n) == n && uniqueList.indexOf( n ) < 0 ) {
						uniqueList.push( n );
					}
				}
			}

			return uniqueList;
		}
		// return empty array if parameter is not an Array.
		else return [];
	}

	var list1 = unique( [1,2,2,2,1,4,6,7,10,1] );
	console.log('list1: ', list1);
	var list2 = unique( [5, 3, 9, 0] );
	console.log('list2: ', list2);

	var list3 = unique( [] );
	console.log('list3: ', list3);

	var list4 = unique( ['a'] );
	console.log('list4: ', list4);

	var list5 = unique( [1.8] );
	console.log('list5: ', list5);