Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 989
  • Last Modified:

jquery get unique values from array

So lets say i have an array

var arr1 = ["jeff","bob","jeff","bob","joe","jeff","jeff"];

how can in jquery(preferrably) or javascript get another array arr2 with only the unique values by order of first occurence so

arr2 = ["jeff","bob","joe"];
0
Brant Snow
Asked:
Brant Snow
  • 2
1 Solution
 
leakim971PluritechnicianCommented:
Using this :

var arr1 = ["jeff","bob","jeff","bob","joe","jeff","jeff"];
		var arr2 = [];
		for(var i=0;i<arr1.length;i++) {
		   var found = false;
		   for(var j=0;j<arr2.length;j++) {
			  if(arr1[i] == arr2[j]) {
				   found = true;
				   break;
			  }
		   }
		   if(!found) arr2.push(arr1[i]);
		}

Open in new window

0
 
leakim971PluritechnicianCommented:
Test page :


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script language="javascript">
	window.onload = function() {
		var arr1 = ["jeff","bob","jeff","bob","joe","jeff","jeff"];
		var arr2 = [];
		for(var i=0;i<arr1.length;i++) {
		   var found = false;
		   for(var j=0;j<arr2.length;j++) {
			  if(arr1[i] == arr2[j]) {
				   found = true;
				   break;
			  }
		   }
		   if(!found) arr2.push(arr1[i]);
		}
		
		// checking 
		for(var i=0;i<arr2.length;i++) {
			alert(arr2[i]);
		}
	}
</script>
</head>
<body>
</body>
</html>

Open in new window

0
 
ProculopsisCommented:

// This is quite a neat solution:

Array.prototype.distinct = function() {
  var unique = new Object();
  var index = -1;
  while ( ++index != this.length ) unique[this[index]] = null;
  var result = new Array();
  for ( var entry in unique ) result.push( entry );
  return result;
};


var arr1 = ["jeff","bob","jeff","bob","joe","jeff","jeff"];

var arr2 = arr1.distinct();

alert( arr2 );
0

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now