How do I push items to array with a for loop? - javascript

Push items on to "entrants" array not working. Anybody know why?
<script>
function taz() {
var entrants = [];
for (var i = 1; i <= 48; i++) {
entrants.push('#P' + i);
}
return entrants;
alert(entrants.length);
console.log(taz());
}
</script>

If you absolutely need the keys to be named, you're looking for an object rather than an array.
function taz() {
var entrants = {};
for (var i = 1; i <= 48; i++) {
entrants['P' + i] = 'Some Value' + i;
}
return entrants;
}
console.log(taz());
However, it might make more sense to store the data in an array, in which case you wouldn't have named keys.
function taz() {
var entrants = [];
for (var i = 1; i <= 48; i++) {
entrants.push('Some Value' + i);
}
return entrants;
}
console.log(taz());

Related

Object doesn't return the maximum number - JS

I was trying to return the maximum repeated word. However for some reason it doesn't return the max. Here's the code responsible for that:
var max = -Infinity;
for(var prop in myObj){
if(myObj[prop] > max){
max = prop;
}
}
return max;
This one returns "h" w/c is the first element in the word 'helllo'...it supposed to be 'l'...
Right now here's my whole codes:
function findMaxRepeatCountInWord(word) {
var splitWord = word.split('');
var myObj = {};
for(var i = 0; i < splitWord.length; i++){
if(myObj.hasOwnProperty(splitWord[i])){
myObj[splitWord[i]]++;
}else{
myObj[splitWord[i]] = 1;
}
}
var max = -Infinity;
for(var prop in myObj){
if(myObj[prop] > max){
max = prop;
}
}
return max;
}
console.log(findMaxRepeatCountInWord('helllo'));
Any idea what am I missing out?
You are comparing a value at first and then you change max to a key.
I suggest to use max only for the key, with a initializing with the first element of the keys. Then iterate from the second key and check if the value is gereater then the actual max value.
function findMaxRepeatCountInWord(word) {
var splitWord = word.split('');
var myObj = {};
for (var i = 0; i < splitWord.length; i++) {
if (myObj.hasOwnProperty(splitWord[i])) {
myObj[splitWord[i]]++;
} else {
myObj[splitWord[i]] = 1;
}
}
var keys = Object.keys(myObj), // take the keys in an array
max = keys[0]; // initialize with the first key
for (i = 1; i < keys.length; i++) { // iterate from the second key
if (myObj[keys[i]] > myObj[max]) { // check and
max = keys[i]; // update
}
}
return max;
}
console.log(findMaxRepeatCountInWord('helllo'));
max is one of the keys. You should compare the value of that key with the current key prop:
if(myObj[prop] > myObj[max])
// ^^^^^^ ^
Simply loop through each character of the text, then store the occurrence in an object
var getMaxOccurence = function (text)
{
var maxObj = {};
// loop through each character
for (var i = 0; i < text.length; i++)
{
var char = text.charAt(i);
// check if char is in obj
if (!(char in maxObj))
{
// add occurrence
maxObj[char] = 1;
}
else
{
// add occurrence
maxObj[char]++;
}
}
var max = {
value: 0,
key: 0
};
var keys = Object.keys(maxObj);
// here get which character contains the highest value.
for (var i = 0; i < keys.length; i++)
{
if (maxObj[keys[i]] > max.value)
{
max.value = maxObj[keys[i]];
max.key = keys[i];
}
}
// return it
return max;
};
document.getElementById("subject").innerHTML = "helllo";
var result = getMaxOccurence("helllo");
document.getElementById("result").innerHTML = result.key + " ( " + result.value + " ) ";
Subject: <span id="subject"></span>
<br/>
Max occurence: <span id="result"></span>
hope that helps

Push object in Javascript

I need to push object to array in Javascript, but every time push overwrite the same object I have had already added. For example:
//This is object list
var NewIssue = {};
//This is array
var newIssueList = [];
function myFunction() {
for (var i = 0; i < 3; i++) {
NewIssue.Id = i;
NewIssue.Number = 233 + i;
NewIssue.Name = "Test" + i.toString();
newIssueList.push(NewIssue);
}
}
In the end I will have newIssueList with 3 same objects. Why it does overwrite the first and how to solve this problem?
You have to move the object inside the loop.
var newIssueList = [];
function myFunction() {
for (var i = 0; i < 3; i++) {
var NewIssue = {};
NewIssue.Id = i;
NewIssue.Number = 233 + i;
NewIssue.Name = "Test" + i.toString();
newIssueList.push(NewIssue);
}
}
myFunction();
console.log(newIssueList);
And then you could just extend the object literal a but to make it much more readable:
for (var i = 0; i < 3; i++) {
var NewIssue = {
Id:i,
Number:233+i,
Name:"Test"+i
};
newIssueList.push(NewIssue);
}
You can also avoid using a superfluous var by creating an inline object:
newIssueList.push({
Id: i,
Number: 233 + i,
Name: "Test" + i.toString()
});
There is only one object, and each time you push it into the array, you push a reference to the existing object. When you change the object, every element in the array reflects this, as they all point to the same object.
You need to create a new object on every iteration.
//This is array
var newIssueList = [];
function myFunction() {
for (var i = 0; i < 3; i++) {
newIssueList.push({
id: i,
number: 233 + i,
name: "Test" + i.toString()
});
}
}
myFunction();
console.log(newIssueList);

javascript array - increment value at given key

I have a dynamic array and I am trying to increment the value by 1 if the key exists in the array. According to my debug it is incrementing the key and and creating a second key/value pair.
A snippet of my code:
for (var i = 0; i < choices.length; i++) {
console.log(choices[i]);
if (choices[i].YearTermId == 1) {
if (!lookup(firstChoice, choices[i].FirstChoiceOptionId)) {
firstChoice.push({
key: choices[i].FirstChoiceOptionId,
value: 1
});
} else {
firstChoice[choices[i].FirstChoiceOptionId] = firstChoice[choices[i].FirstChoiceOptionId] + 1;
}
more if/else..
function lookup( arr, name ) {
for(var i = 0, len = arr.length; i < len; i++) {
if( arr[ i ].key === name )
return true;
}
return false;
}
You're using an array where you should be using an object. If you use an object, your code can be rewritten as:
var firstChoice = {};
for (var i = 0; i < choices.length; i++) {
var firstChoiceOptionId = choices[i].FirstChoiceOptionId;
if (choices[i].YearTermId == 1) {
firstChoice[firstChoiceOptionId] = firstChoice[firstChoiceOptionId]
? firstChoice[firstChoiceOptionId] + 1
: 1;
/* ... */
}
}
If you need the data as an array afterwards, just map it:
var firstChoiceArray = Object.keys(firstChoice).map(function(key) {
return {
key: key,
value: firstChoice[key]
};
});
Conversely, if you have an input array and want to convert it to an object for manipulation, reduce it:
var firstChoice = firstChoiceArray.reduce(function(result, current) {
result[current.key] = current.value;
return result;
}, {});
I think you should increment value key, like:
firstChoice[choices[i].FirstChoiceOptionId].value ++;
And I would like to rewrite this code to:
var firstChoice = {};
for (var i = 0; i < choices.length; i++) {
if (choices[i].YearTermId == 1) {
if (!firstChoice[choices[i].FirstChoiceOptionId]) {
firstChoice[choices[i].FirstChoiceOptionId] = 0;
}
firstChoice[choices[i].FirstChoiceOptionId]++;
}
}
console.log(firstChoice);
Try with Array.map:
Example:
var a = [{key:"ab","value":1},{key:"cd","value":1},{key:"ef","value":1}];
a.map(function(item){if(item.key == this){item.value++}}, "cd");
So, a[1] will have value 2 after that.

Multiplying all numbers in two arrays in javascript

As an exercise, I'm trying to create a function that returns the palindromic numbers resulting from multiplying three-digit numbers. As far as I can tell, the function is running through numbers correctly, however, the resulting array is incorrect. I don't need the solution to the palindrome problem...just an idea of what I might be missing. Have I run into some limitation?
var palindromic = function() {
var a = [];
var res = [];
for (var i = 100; i < 1000; i++) {
a.push(i);
}
var ar = a.slice(0);
a.map(function(x) {
for (var j = 0; j < ar.length; j++) {
var result = x * ar[j];
if (result.toString() === result.toString().split("").reverse().join("")) {
res.push(result);
}
}
})
return res;
};
Pretty sure it's just trying to call console.log() 810,000 times. If you comment the console.log line, it works just fine.
var palindromic = function() {
var a = [];
var res = [];
for (var i = 100; i < 1000; i++) {
a.push(i);
}
var ar = a.slice(0);
a.map(function(x) {
for (var j = 0; j < ar.length; j++) {
var result = x * ar[j];
//console.log(x + " : " + ar[j] + ' = ' + result);
if (result.toString() === result.toString().split("").reverse().join("")) {
res.push(result);
}
}
});
return res;
};
console.log(palindromic());

How do I merge a list of results into a compacted object with totals

I'm looping through a set of inputs. I need to tally up the grouped totals.
var compoundedArray = new Array();
holder.find(".dataset input").each(function(index) {
var val = $(this).val();
var dataType = $(this).data("type");
var localObj = {};
localObj[dataType] = val;
compoundedArray.push(localObj);
});
I have an object like this
[
{
"growth":30
},
{
"growth": 40
},
{
"other": 20
}
]
how do I loop through the object to produce something like
[
{
"growth": 70
},
{
"other": 20
}
]
if I looped over the initial array object
for (var i = 0; i < compoundedArray.length; i++) {
console.log(compoundedArray[i]);
}
how would I go about checking to ensure I don't have duplicates - and that I can tally up the results?
I think your selection of data structure is a bit too complicated. Try something like.
var compoundedObject = {};
holder.find(".dataset input").each(function(index) {
var val = $(this).val();
var dataType = $(this).data("type");
//Assuming all values are integers and can be summed:
if( compoundedObject.hasOwnProperty(dataType) )
{
compoundedObject[dataType] += val;
}
else
{
compoundedObject[dataType] = val;
}
});
You will end up with an object, not an array though.
var add=function (a,b){ a=a||0; b=b||0; return a+b};
var input=[ {growth:30},{growth:40},{other:20} ],output=[],temp={};
$.each(input,function(i,o){
var n;
for(i in o)
{n=i;break}
temp[n]=add(temp[n],o[n]);
});
$.each(temp,function(i,o){
var k={};
k[i]=o;
output.push(k)
});
find output at output variable.
Do not post much specific question, It might not help others.
This works. And it's pure javascript.
var totals = {};
for (var i = 0; i < compoundedArray.length; i++) {
var item = compoundedArray[i];
for (var key in item) {
totals[key] = (totals[key] || 0) + item[key]
}
};
You can loop trough an Object with a for loop.
If you want to delete an item simply set it to null.
Example:
for(var i in compoundedArray){
for(var j in compoundedArray){
if(i == j){
compoundedArray[i] += compoundedArray[j];
compoundedArray[j] = null;
}
}
}
You can do the following:
var totals = [], tmp = {};
for (var i = 0; i < compoundedArray.length; i++) {
var obj = compoundedArray[i];
for (var j in obj) {
tmp[j] = tmp[j] || 0;
tmp[j] += obj[j];
}
}
for(var k in tmp) {
var obj = {};
obj[k] = tmp[k];
totals.push(obj);
}
See this working demo

Categories

Resources