...

View Full Version : Pushing array into an Object



bunzu
07-19-2012, 04:42 AM
Hello All,

I'm trying to do the following:
- Inside my array I want to keep track of what is a dupe but I don't know how to go about it.
- Since I have to 2 letter a I want it to say something like { 'a', count=2 }

This is what I have so far:


array = ['a','b','c','d','c']
var alphabet = {};
var count = [];

for (a=0; a<array.length; a++){
myCount = 0;

alphabet.value = array[a];
alphabet.count = myCount;
count.push(alphabet);
}
console.log(alphabet); // returns Object { value="c", count=0 }

jmrker
07-19-2012, 05:17 AM
<html>
<head>
<title> Untitled </title>
<script type="text/javascript">
var alphaArray = ['a','b','c','d','c'];
var counts = [];
for (var a=0; a<alphaArray.length; a++){
if (counts[alphaArray[a]] == undefined) { counts[alphaArray[a]] = 1; }
else { counts[alphaArray[a]]++; }
}
var str = 'Occurances in array\n\n';
for (var indx in counts) { str += indx+' : '+counts[indx]+'\n'; }
alert(str);
</script>
</head>
<body>

</body>
</html>

bunzu
07-19-2012, 05:41 AM
Thanks jmrker. :)

Philip M
07-19-2012, 08:26 AM
The following will remove duplicates from an aray:-


<script type = "text/javascript">

removeDuplicated = function(a, s){
var p, i, j;
if(s) for(i = a.length; i > 1;){
if(a[--i] === a[i - 1]){
for(p = i - 1; p-- && a[i] === a[p];);
i -= a.splice(p + 1, i - p - 1).length;
}
}
else for(i = a.length; i;){
for(p = --i; p > 0;)
if(a[i] === a[--p]){
for(j = p; --p && a[i] === a[p];);
i -= a.splice(p + 1, j - p).length;
}
}
return a;
};
</script>



<script type = "text/javascript">

var arr = ["Philip", "Tom","Peter", "Tom", "Tony", "Philip", "Mary"];
b = arr.slice().sort();

document.write("<h2>Original Array</h2>A = ", arr.join(","),
"<br />removeDuplicated(A) = ", removeDuplicated(arr),
"<br /><h2>Original Sorted Array</h2>B = ", b.join(","),
"<br />removeDuplicated(B, true) = ", removeDuplicated(b, true)
);

</script>



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum