This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
JavaScript: Getting random value from an array
How can I choose an object key at random?
suppose we have an array like this:
var MrArray = new Array(5);
MrArray['one']='oneValue';
MrArray['two']='twoValue';
MrArray['three']='threeValue';
MrArray['four']='fourValue';
MrArray['five']='fiveValue';
ok?
the Array is associated.
and we have string key and string value.
now! how can i pick a random value from that?
Edit:i want to use like this:
Array Key Here
Regards
Sam
Using the method described here we can create the following function:
function randomKey(obj) {
var ret;
var c = 0;
for (var key in obj)
if (Math.random() < 1/++c)
ret = key;
return ret;
}
It returns a random key, so to get a random value from MrArray, do this:
var value = MrArray[randomKey(MrArray)];
jsPerf benchmark comparing the speed of this and the other answer.
Here:
function fetch_random(obj) {
var temp_key, keys = [];
for(temp_key in obj) {
if(obj.hasOwnProperty(temp_key)) {
keys.push(temp_key);
}
}
return obj[keys[Math.floor(Math.random() * keys.length)]];
}
Src: How can I choose an object key at random?
Related
This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Is it possible to add dynamically named properties to JavaScript object?
(20 answers)
Closed 2 years ago.
I'm trying to find out how to initialise an array of objects, where each object has the index (i) as its key and 0 as its value. The code below is not working as expected but I can't see why. I'm still quite beginner with Javascript and couldn't find an answer elsewhere.
var n = 10;
var sample = [];
for (var i = 0; i < n; i++)
sample.push({i : 0});
you should use this syntax sample.push({[i]: 0});
when you need to access object property which is stored under some variable you should always use square brackets no matter you need write to or read from an object
The code below should take care of the job:
let n = 10;
let sample = Array.from({length:n}, (_, i) => ({ [i]: 0 }));
As pointed by Oleksandr Sakun on his answer, the index is used between brackets in order to evaluate the variable and set as a property of the object.
For a funcitonal approach you can try:
const initArray = (n)=>{
const newArr = new Array(n).fill(0);
return newArr.map((value, index)=> ({[index]: value}))
}
add square brackets to the index [i] :
var n = 10;
var sample = [];
for (var i = 0; i < n; i++)
sample.push({[i]: 0});
console.log(sample);
This question already has answers here:
Merge keys array and values array into an object in JavaScript
(14 answers)
Closed 1 year ago.
I'm using local storage to get an arrays of strings,
First value attrIds is as follows,
var attrIds = localStorage.getItem('attributeids');
attrIds = JSON.parse(attrIds);
Second value confOptions is as follows,
I want something like this,
144: "5595"
93: "5487"
I have tried creating a loop inside the loop and tried to set the key and value but it's not working. I have also tried to set the single JSON object as key and setting value as '' but couldn't move further with that.
Does anyone have any idea regarding this?
You can accomplish this using a simple for loop, accessing the items from the arrays, and assigning properties to an empty object.
const keys = ['144', '93'];
const values = ['5595', '5487'];
const obj = {};
for (let i = 0; i < keys.length; i++) {
obj[keys[i]] = values[i];
}
console.log(obj); // prints { 144: '5595', 93: '5487' }
Create a nested array and then use Object.fromEntries().
const
a = ["144", "93"],
b = ["5595", "5487"],
c = Object.fromEntries(a.map((v, i) => [v, b[i]]));
console.log(c);
Using a for loop, you could do something like:
var attrIds = localStorage.getItem('attributeids');
attrIds = JSON.parse(attrIds);
confOptions = ["5595", "5487"]
const object = {};
for(let i=0; i<attrIds.length;i++)
object[attrIds[i]] = confOptions[i]
This question already has answers here:
Algorithm to return all combinations of k elements from n
(77 answers)
Closed 7 years ago.
I need to be able to take a list of strings, and come up with a list of all possible combinations of those strings combined.
["asdf", "ghj","ew","ptum"]
It should get a list something like this, up to n
["agep", "aget", "ageu", ... "fjwm"]
What would I do to get these?
What you are asking is relatively trivial... some for loops can do this fairly easily. Below is one such method you could use.
var input = ["asdf", "ghj", "ew", "ptum"];
function combinations(r, n) {
var o = [];
if (r.constructor.name === "String")
r = r.split("");
if (n.constructor.name === "String")
n = n.split("");
r.forEach(function(i) {
n.forEach(function(j) {
o.push(i + j);
})
})
return o;
}
document.write("<pre>"+JSON.stringify(input.reduce(combinations),null,2)+"</pre>");
You can create an array of letters from the list of strings , like in your case ->
list of strings :
list = ["asdf", "ghj","ew","ptum"]
array of letters would be :-
arr = ["a","s",...,"m"]
then iterate through the array, for each letter make combination with other letters in array ...
the logic will be like this...
//for strings of length 3 ..
for(i in arr){
for(j in arr){
for(k in arr){
if(i!=j && j!=k)
result=i+j+k
}
}
}
p.s I am not into JS , I just told one logic to do this , you can now implent the logic in your language.
This question already has answers here:
How to keep an Javascript object/array ordered while also maintaining key lookups?
(2 answers)
Closed 7 years ago.
I have got a function which retrieves an object.
This object has a property and a value. The property is numeric and starts at "-30" all the way up to "50"
The problem is that when I loop through this object the browser seems to order it starting at "0" instead of starting at the initial property of "-30"
I need to make sure the order is exactly the same as the object.
var colorOj = {
"-30":"#111","-29":"#131313", ..etc.., "0":"#333", ..etc..,
"50":"#555"
}
function makeList(object){
for (var i in object) {
console.log(i); // Returns 0,1,2,3,4,5
// I need a return of -30,-29,-28,..., 0, 1, 2 ...
}
}
makeList(colorObj);
As suggested by #Teemu, properties are not stored in any specific order. But you can print them in any order using specific sort function accordingly.
Code
var obj = {};
for (var i = 5; i > -5; i--) {
obj[i * 10] = i * 10;
}
// Sort and get all keys...
var keys = Object.keys(obj).sort(function(a, b) {
return parseInt(a) - parseInt(b);
});
console.log(keys)
// Loop over keys to print values of each property
keys.forEach(function(item) {
console.log(item, obj[item]);
})
You can do something like this maybe:
var colorOj = {
"-30":"#111","-29":"#131313", "0":"#333",
"50":"#555"
};
var keys = Object.keys(colorOj).sort(function(a,b){return a - b})
for(var i = 0; i < keys.length;i++){console.log(keys[i])}
This way you can get every key in the object. Then sort it however you like(the sort function in javascript can take a compare function as a parameter look -> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)
This question already has answers here:
Length of a JavaScript object
(43 answers)
Closed 3 years ago.
I'm trying to check the length here. Tried count. Is there something I'm missing?
var dNames = {};
dNames = GetAllNames();
for (var i = 0, l = dName.length; i < l; i++)
{
alert("Name: " + dName[i].name);
}
dNames holds name/value pairs. I know that dNames has values in that object but it's still completely skipping over that and when I alert out even dName.length obviously that's not how to do this...so not sure. Looked it up on the web. Could not find anything on this.
What I do is use Object.keys() to return a list of all the keys and then get the length of that
Object.keys(dictionary).length
var c = {'a':'A', 'b':'B', 'c':'C'};
var count = 0;
for (var i in c) {
if (c.hasOwnProperty(i)) count++;
}
alert(count);
This question is confusing. A regular object, {} doesn't have a length property unless you're intending to make your own function constructor which generates custom objects which do have it ( in which case you didn't specify ).
Meaning, you have to get the "length" by a for..in statement on the object, since length is not set, and increment a counter.
I'm confused as to why you need the length. Are you manually setting 0 on the object, or are you relying on custom string keys? eg obj['foo'] = 'bar';. If the latter, again, why the need for length?
Edit #1: Why can't you just do this?
list = [ {name:'john'}, {name:'bob'} ];
Then iterate over list? The length is already set.
Count and show keys in a dictionary (run in console):
o=[];count=0; for (i in topicNames) { ++count; o.push(count+": "+ i) } o.join("\n")
Sample output:
"1: Phase-out Left-hand
2: Define All Top Level Taxonomies But Processes
3: 987
4: 16:00
5: Identify suppliers"
Simple count function:
function size_dict(d){c=0; for (i in d) ++c; return c}