i have a dynamic array as below which will display in the Hightchat and using date as a index for the same
[34,23,44,34,0,0,23,23,40,0,0,0,0,0,10]
after this will sort the array and get first 10 highest list of array as below
[44,40,34,34,23,23,23,10,0,0]
issues i am facing here is for repeated numbers like (34,34,23,23....) i am getting same date as a index for example( consider for 34 i have and a date 23/04/2017 as a index.. same date is displayed for both the number(34,34)..
kindly help me out to get the respective index for repeated values in an array..
please reply back if you need more info
var A = [34,23,44,34,0,0,23,23,40,0,0,0,0,0,10];
var B = ['23/04/2017','24/04/2017','25/04/2017','26/04/2017','27/04/2017','28/04/2017','29/04/2017','30/04/2017','01/05/2017','02/05/2017','03/05/2017','04/05/2017','05/05/2017','06/05/2017','07/05/2017'];
var all = [];
for (var i = 0; i < B.length; i++) {
all.push({ 'A': A[i], 'B': B[i] });
}
all.sort(function(a, b) {
return b.A - a.A;
});
A = [];
B = [];
for (var i = 0; i < 10; i++) {
A.push(all[i].A);
B.push(all[i].B);
}
console.log(A, B);
This solution can solve your problem please have a look on these It will gives you the result which expected.
I am sorting using hash so that each key have correct value.
Related
Newer to coding and javascript and I am trying a codewars challenge. I setup an array to repeat a letter at certain indexes of my newArray based on a loop. For example if input was: cwAt expected output should be: C-Ww-Aaa-Tttt.
Been stuck on this for several hours (and have slept on it). I get error code:
newArray.join is not a function
when I try to run this and not sure what I can do to fix this problem. I feel its something simple and I just need to learn why this is happening.
function accum(s) {
let mumble = s.split('');
for (i = 0; i < mumble.length; i++) {
let newArray = [mumble[i].toUpperCase(), ''];
for (j = i; j > 0; j--) {
newArray = newArray.push(mumble[i]);
};
// Merge the new array into a string and set it at the mumble index required
mumble[i] = newArray.join('');
};
//Return new mumble with - as spaces between elements
return mumble.join('-');
}
console.log(accum('cwAt'));
Change newArray = newArray.push(mumble[i]); to newArray.push(mumble[i]);
push returns new length of the array.
You are storing a number in newArray. Try replace the 4 line with:
let newArray[i] = [mumble[i].toUpperCase(), ''];
and the 5 line :
for (j = 0; j < 0; j++) {
and the 6:
newArray[j] = newArray.push(mumble[i]);
How to generate an array with function like this?
var name = ["monkey","monkey"..."horse","horse",..."dog","dog",..."cat","cat"...]
In my real case, I may have to repeat each name 100 times..
Assuming that you already have that words in a array try this code:
var words = ["monkey", "hourse", "dog", "cat"];
var repeatWords = [];
for(var i = 0; i < words.length; i++)
{
for(var j = 0; j < 100; j++)
{
repeatWords.push(words[i]);
}
}
You can try this, specifying the words to be used, and the times to create the array you need.
var neededWords = ["Cat", "Hourse", "Dog"];
var finalArray = [];
var times = 10;
for (var i = 0; i < neededWords.length; i++) {
for (var n = 0; n < times; n++) {
finalArray.push(neededWords[i]);
}
}
console.log(finalArray);
Hope that helps!
If I understood correctly you need a function that takes as an argument a collection of items and returns a collection of those items repeated. From your problem statement, I assumed that the repetition has to be adjusted by you per collection item - correct me if I am wrong.
The function I wrote does just that; it takes an object literal {name1:frequency1,name2:frequency2..} which then iterates over the keys and pushes each one as many times as indicated by the associated frequency in the frequencyMap object.
function getRepeatedNames( frequencyMap ) {
var namesCollection = [];
Object.keys(frequencyMap).forEach(function(name,i,names){
var freq = frequencyMap[name];
freq = (isFinite(freq)) ? Math.abs(Math.floor(freq)) : 1;
for (var nameCounter=0; nameCounter<freq; nameCounter++) {
namesCollection.push(name);
}
});
return namesCollection;
}
Non-numeric values in the frequency map are ignored and replaced with 1.
Usage example: If we want to create an array with 5 cats and 3 dogs we need to invoke
getRepeatedNames({cat: 2, dog: 3}); // ["cat","cat","dog","dog","dog"]
I want to display an array without showing of indexes. The for loop returns the array indexes which is not showing in usual declaration.
I want to send an array like [1,2,3 ...] but after retrieving from for loop, I haven't the above format. How can I store my values as above.
var a = [];
for (var i = 1; i < 8; i++) {
a[i] = i;
};
console.log(a);
Outputs:
[1: 1, 2: 2 ...]
Desired output:
[1,2,3]// same as console.log([1,2,3])
Array indices start at zero, your loop starts at 1, with index 0 missing you have a sparse array that's why you get that output, you can use push to add values to an array without using the index.
var a = [];
for (var i = 1; i < 8; i++) {
a.push(i);
};
console.log(a);
The problem is that you start your array with 1 index, making initial 0 position being empty (so called "hole" in array). Basically you treat array as normal object (which you can do of course but it defeats the purpose of array structure) - and because of this browser console.log decides to shows you keys, as it thinks that you want to see object keys as well as its values.
You need to push values to array:
var a = [];
for (var i = 1; i < 8; i++) {
a.push(i);
};
I have to disagree with the answers provided here. The best way to do something like this is:
var a = new Array(7);
for (var i = 0; i < a.length; i++) {
a[i] = i + 1;
}
console.log(a);
Your code is making each index equal to i, so use it this way
var a = [];
for (var i = 1; i < 8; i++) {
a.push(i);
};
console.log(a);
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
I have a comma separated string, out of which I need to create a new string which contains a random order of the items in the original string, while making sure there are no recurrences.
For example:
Running 1,2,3,1,3 will give 2,3,1 and another time 3,1,2, and so on.
I have a code which picks a random item in the original string, and then iterates over the new string to see if it does not exist already. If it does not exist - the item is inserted.
However, I have a feeling this can be improved (in C# I would have used a hashtable, instead of iterating every time on the new array). One improvement can be removing the item we inserted from the original array, in order to prevent cases where the random number will give us the same result, for example.
I'd be happy if you could suggest improvements to the code below.
originalArray = originalList.split(',');
for (var j = 0; j < originalArray.length; j++) {
var iPlaceInOriginalArray = Math.round(Math.random() * (originalArray.length - 1));
var bAlreadyExists = false;
for (var i = 0; i < newArray.length; i++) {
if (newArray[i].toString() == originalArray[iPlaceInOriginalArray].toString()) {
bAlreadyExists = true;
break;
}
}
if (!bAlreadyExists)
newArray.push(originalArray[iPlaceInOriginalArray]);
}
Thanks!
You can still use a 'hash' in javascript to remove duplicates. Only in JS they're called objects:
function removeDuplicates(arr) {
var hash = {};
for (var i=0,l=arr.length;i<l;i++) {
hash[arr[i]] = 1;
}
// now extract hash keys... ahem...
// I mean object members:
arr = [];
for (var n in hash) {
arr.push(n);
}
return arr;
}
Oh, and the select random from an array thing. If it's ok to destroy the original array (which in your case it is) then use splice:
function randInt (n) {return Math.floor(Math.random()*n)}
function shuffle (arr) {
var out = [];
while (arr.length) {
out.push(
arr.splice(
randInt(arr.length),1 ));
}
return out;
}
// So:
newArray = shuffle(
removeDuplicates(
string.split(',') ));
// If you sort the first array, it is quicker to skip duplicates, and you can splice each unique item into its random position as you build the new array.
var s= 'Function,String,Object,String,Array,Date,Error,String,String,'+
'Math,Number,RegExp,Group,Collection,Timelog,Color,String';
var A1= s.split(',').sort(), A2= [], tem;
while(A1.length){
tem= A1.shift();
while(A1[0]== tem) tem= A1.shift();
if(tem) A2.splice(Math.floor(Math.random()*A2.length), 0, tem);
}
alert(A2.join(', '))
With your solution, you are not guaranteed not to pick same number several times, thus leaving some others of them never being picked. If the number of elements is not big (up to 100), deleting items from the source array will give the best result.
Edit
originalArray = originalList.split(',');
for (var j = 0; j < originalArray.length; j++) {
var iPlaceInOriginalArray = Math.round(Math.random() * (originalArray.length - 1 - j));
var bAlreadyExists = false;
for (var i = 0; i < newArray.length; i++) {
if (newArray[i].toString() == originalArray[iPlaceInOriginalArray].toString()) {
bAlreadyExists = true;
break;
}
}
var tmp = originalArray[originalArray.length - 1 - j];
originalArray[originalArray.Length - 1 - j] = originalArray[iPlaceInOriginalArray];
originalArray[iPlaceInOriginalArray] = tmp;
if (!bAlreadyExists)
newArray.push(originalArray[iPlaceInOriginalArray]);
}