Count number of ocurrences in an array [duplicate] - javascript

This question already has answers here:
Counting the occurrences / frequency of array elements
(39 answers)
Closed 7 years ago.
I'm interested in finding out how many times every object in an array occurs.
Here's what I want to do mixed with some pseudo-code of what I think is the way to do it.
var myArray = [1,2,3,1,1,3,4];
for (i = 0; i < myArray.length; i++) {
if (myArray[i].AlreadyExistsInAVariable) {
var[i]+ = 1;
}
else {
CreateAnewVar();
}
}
var one = 3;
var two = 1;
var three = 2;
var four = 1;

You should use object to count the occurence of numbers in the array rather than using variables.
var myArray = [1,2,3,1,1,3,4];
var counter = {};
for (i = 0; i < myArray.length; i++) {
if (myArray.indexOf(myArray[i])>=0) {
if(!counter[myArray[i]]){
counter[myArray[i]]=1;
}
else{
counter[myArray[i]]++;
}
}
}
console.log(counter);

How about this:
var myArray = [1,2,3,1,1,3,4];
var count = myArray.reduce(function(n, val) {
return n + (val === 1);
}, 0);
console.log(count);
Edit:
For counting occurrences of every element in an array i would do something like this:
var result = {};
[1,2,3,1,1,3,4].forEach(function(e, i) {
result[e] = result[e] + 1 || 1;
});
alert(JSON.stringify(result, null, "\t"));

You can't actually just create new variable bindings like that. You can, however, dynamically add new properties to an object, which is probably a better match for this problem. Here's an example that counts up the occurrences of numbers in that array:
var myArray = [1,2,3,1,1,3,4];
var counts = myArray.reduce(function(result, item) {
result[item] || (result[item] = 0);
result[item]++;
return result;
}, {});
console.log(counts);
See it in action here: http://jsbin.com/huduroyite/edit?js,console

Related

How to create javascript array when each element is a pair of objects

hello I would like to build an array that every element will be a pair of objects , Something like this
var Shelves = new arr[][]
var books = new Books[] ;
Shelves[book[i],book[j=i+1]],[book[i+1],book[j=i+1]] and so on......;
I mean that I understand how to go with a for loop and to get the elements 'but how to push them in pairs array? arr.push doesn't work :(
build1ArrPairs(1Arr) {
if (1Arr != undefined || 1Arr!=null) {
for (var i = 0; i < 1Arr.length; i = i + 1) {
for (var j = i + 1; j <= 1Arr.length; j++) {
this.1ArrPair.push(1Arr[i] 1Arr[j]);
break;
}
}
}
}
Thanks :)
Alternatively, you can use array#reduce to group your array.
var names = ['a', 'b','c','d','e'];
var result = names.reduce((r,w,i) => {
let index = Math.floor(i/2);
if(!Array.isArray(r[index]))
r[index] = [];
r[index].push(w);
return r;
},[]);
console.log(result);
First of all, variables names can't start with a number.
Second, initialize an array, then add your elements - two at a time - and return the array:
var ans = [];
if (Arr != undefined || Arr != null) {
for (var i=0; i<(Arr.length-1); i+=2) { // Note the loop stops 2 elements before the last one
ans.push([Arr[i], Arr[i+1]]);
// ^ Note the comma - it's missing in your code
}
}
return ans;

Arrays inside an array Javascript [duplicate]

This question already has answers here:
How to check if object property exists with a variable holding the property name?
(11 answers)
Closed 5 years ago.
I want to make an array so that it contains some identity name and for each of those names there is another array associated. My approach is like,
for (var i = 0; i < 10; i++) {
for (var x = 0; x < 5; x++) {
var data = someServiceCall(i, x);
var identityName = i + '-' + x;
myArray[identityName] = data;
}
}
after executing this i get something like,
[1-1: Array(8), 1-2: Array(10), 1-3: Array(10), 1-4: Array(10),.. etc]
the next time I call this function I need to check whether 1-1 exists and if yes I need to get the list related to 1-1. How can I do this..? if 1-1 is not in the myArray I will call some other function.
To check if the element having the 1-1 key exists just do:
if("1-1" in myArray)
Then to access the array associated with 1-1 use:
myArray["1-1"]
Try this. It inserts an object containing the identity name and data in each array element.
var myArray = [];
for (var i = 0; i < 10; i++) {
for (var x = 0; x < 5; x++) {
var data = someServiceCall(i, x);
var identityName = i + '-' + x;
var objectInArr = {
'identityName': identityName,
'data' : data
};
myArray.push(objectInArr);
};
};
try like this
myArray["1-1"] != undefined
Check if key exists in your array or not and act accordingly. Following is a working code snippet
var myArray = [];
for (var i = 0; i < 10; i++) {
for (var x = 0; x < 5; x++) {
var identityName = i + '-' + x;
myArray[identityName] = [1, 2];
}
}
var key = "0-0";
if(myArray[key])
console.log(myArray[key]);
you can check your array lenght and if the array is empty you will know that you need to call another action as you say. something like below might work for you
if (myArray.length === 0) {
//Call another function}
else {
//Somthing else}

Is it possible to access all elements in an Array randomly using a for loop? [duplicate]

This question already has answers here:
How to randomize (shuffle) a JavaScript array?
(69 answers)
Closed 6 years ago.
I have an array
var array = ["what","is","going","on"];
I know it's possible to access and list these elements with a standard for loop like so:
for (i = 0; i <= array.length; i++) {
console.log(array[i]);
}
But I want to know if there's a way to list these elements in a random order. I suspect that I have to use some variation of Math. but I don't have enough experience to decide which to use for sure. Thanks in advance!
You should first shuffle the array and then read one by one. An array method like Array.prototype.shuffle() might come handy.
Array.prototype.shuffle = function(){
var i = this.length,
j,
tmp;
while (i > 1) {
j = Math.floor(Math.random()*i--);
tmp = this[i];
this[i] = this[j];
this[j] = tmp;
}
return this;
};
var arr = [1,2,3,4,5].shuffle();
for(var i = 0; i < arr.length; i++) console.log(arr[i]);
Statistically speaking, this will definitely work. It just may take until the heat-death of the universe to complete.
var array = ["What", "am", "I", "doing", "with", "my", "life"];
var processed = [];
function randomAccess() {
if (processed.length === array.length) {
console.log('Done!');
return;
}
var index = Math.floor(Math.random() * array.length);
if (processed.indexOf(index) === -1) {
// Make sure we haven't processed this one before
console.log('array[' + index + ']:', array[index]);
processed.push(index);
}
// Prevent locking up the browser
setTimeout(randomAccess, 0);
}
randomAccess();
Please don't use this in production code. Theoretically, it may never complete.
Yes, you can introduce a second array to log the indices you have randomly returned - in order not to return the same index more than once.
Working example:
var myArray = ['what','is','going','on'];
var returnedIndices = [];
for (i = 0; i < myArray.length; i++) {
var randomIndex = Math.floor(Math.random() * myArray.length);
if (returnedIndices.indexOf(randomIndex) !== -1) {
i--;
continue;
}
else {
returnedIndices[i] = randomIndex;
console.log(myArray[randomIndex]);
}
}
console.log(array[Math.floor(Math.random() * (array.length - 1))]);

Generating random numbers in an array without any duplicate numbers [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm trying to create an array with random number with length of 78. I don't know how to search the entire array and check if last entry was duplicate and remove it. Someone please help.
function initAll() {
var balls = LoadInBingoBalls();
for(i=0; i < balls.length;i++)
{
(balls[i]);
}
}
function setSquare (numSquare) {
var BingoSquare = "square" + numSquare.toString();
document.getElementById(BingoSquare).innerHTML = RandomNumber(MaxNo);
}
var RandomNumber = function (max) {
return Math.floor(Math.random() * max) + 1;
}
function LoadInBingoBalls(){
var first = 0;
var last = 78;
var random;
var bag = [];
//Heres the part i get confused!
for (var i = first; i <= last; i++) {
do
bag.push(i) = setSquare(i);
while(bag.indexOf(i) !== -1)
}
return bag;
}
}
This function will create the array and check to see if it contains the number before pushing:
working example: https://jsbin.com/cabofa/1/edit?js,console
function randNum (max) {
return Math.floor(Math.random() * max) + 1;
}
function makeArray(n) {
var arr = [];
while (arr.length < n) {
var random = randNum(n);
if (arr.indexOf(random) === -1) {
arr.push(random);
}
}
return arr;
}
Create an array with all the possible values:
var possibles = [];
for(i=1; i<=78; i++) {
possibles.push(i);
}
Shuffle that array of values to be random:
function shuffle(a) {
var j, x, i;
for (i = a.length; i; i -= 1) {
j = Math.floor(Math.random() * i);
x = a[i - 1];
a[i - 1] = a[j];
a[j] = x;
}
return a;
}
var shuffled = shuffle(possibles);
Now pop a value from your new array to get a random element from it:
var popped = shuffled.pop();
console.log(popped);
You can call pop() as many times as you want until the array is empty, which will return undefined. For example:
for(i=0; i<shuffled.length; i++) {
console.log(shuffled.pop());
}

Dynamic Array Value Count

Similar to this question - Array value count javascript
How would I go about doing this, except with dynamic values?
var counts = []
var dates= [ "28/05/2013", "27/05/2013", "28/05/2013", "26/05/2013", "28/05/2013" ];
How would I get a count of the duplicated array values? So how many 28/05/2013 etc. The dates are all dynamic, so I can't just search for set values. I just can't get my head around how I would do this.
I may just scrap this idea, and get the value count from the last 10 days or something... but this may come in handy later(if it is even possible to do this).
This will do it:
var counts = {};
for (var i=0; i<dates.length; i++)
if (dates[i] in counts)
counts[dates[i]]++;
else
counts[dates[i]] = 1;
The result will be
> counts
{
"28/05/2013": 3,
"27/05/2013": 1,
"26/05/2013": 1
}
Make counts an object to perform duplicate detection in constant time.
var counts = {}
for (var i = 0; i < dates.length; i++) {
var date = dates[i];
if (counts[date] === undefined) {
counts[date] = 0;
}
counts[date] += 1;
}
console.log(counts);
Try like this
Updated
var dates= [ "28/05/2013", "27/05/2013", "28/05/2013", "26/05/2013", "28/05/2013" ];
var findStr = "28/05/2013";
var indexs = dates.indexOf(findStr,0),count=0;
for (var i=0;i< dates.length;i++){
if (indexs >= 0){
indexs = dates.indexOf(findStr,indexs + 1);
count++;
}
}
alert(count);
See Demo

Categories

Resources