array.push only the last variable in a for loop javascript - javascript

i'm actually asking myself why the following code is not working properly i found the solution but it's a bit tricky and i don't like this solution
Here is the code and the problem:
function powerSet( list ){
var set = [],
listSize = list.length,
combinationsCount = (1 << listSize),
combination;
for (var i = 1; i < combinationsCount ; i++ ){
var combination = [];
for (var j=0;j<listSize;j++){
if ((i & (1 << j))){
combination.push(list[j]);
}
}
set.push(combination);
}
return set;
}
function getDataChartSpe(map) {
var res = {};
for (var i in map) {
console.log("\n\n");
var dataSpe = {certif: false,
experience: 0,
expert: false,
grade: 1,
last: 100,
name: undefined
};
var compMatchList = [];
for (var j in map[i].comps_match) {
var tmp = map[i].comps_match[j];
compMatchList.push(tmp.name)
}
var tmpList = powerSet(compMatchList);
var lol = [];
lol.push(map[i].comps_match);
for (elem in tmpList) {
console.log("mdr elem === " + elem + " tmplist === " + tmpList);
var tmp = tmpList[elem];
dataSpe.name = tmpList[elem].join(" ");
lol[0].push(dataSpe);
}
console.log(lol);
}
return res;
}
now here is the still the same code but working well :
function powerSet( list ){
var set = [],
listSize = list.length,
combinationsCount = (1 << listSize),
combination;
for (var i = 1; i < combinationsCount ; i++ ){
var combination = [];
for (var j=0;j<listSize;j++){
if ((i & (1 << j))){
combination.push(list[j]);
}
}
set.push(combination);
}
return set;
}
function getDataChartSpe(map) {
var res = {};
var mapBis = JSON.parse(JSON.stringify(map));
for (var i in map) {
var compMatchList = [];
for (var j in map[i].comps_match) {
var tmp = map[i].comps_match[j];
compMatchList.push(tmp.name)
}
var tmpList = powerSet(compMatchList);
mapBis[i].comps_match = [];
for (elem in tmpList) {
tmpList[elem].sort();
mapBis[i].comps_match.push({certif: false,
experience: 0,
expert: false,
grade: 1,
last: 100,
name: tmpList[elem].join(", ")});
}
}
return mapBis;
}
Actually it's a bit disapointig for me because it's exactly the same but the 1st one doesn't work and the second one is working.
so if anyone can help me to understand what i'm doing wrong it'll be with pleasure
ps: i'm sorry if my english is a bit broken

In the first version, you build one dataSpe object and re-use it over and over again. Each time this runs:
lol[0].push(dataSpe);
you're pushing a reference to the same single object onto the array.
The second version of the function works because it builds a new object each time:
mapBis[i].comps_match.push({certif: false,
experience: 0,
expert: false,
grade: 1,
last: 100,
name: tmpList[elem].join(", ")});
That object literal passed to .push() will create a new, distinct object each time that code runs.

Related

Push different object in an array with a for loop

I have an element structured like this:
Element ->
[{values: arrayOfObject, key:'name1'}, ... ,{values: arrayOfObjectN, key:'nameN'}]
arrayDiObject -> [Object1, Object2, ... , ObjectN] //N = number of lines in my CSV
Object1 -> {x,y}
I have to take data from a big string:
cityX#substanceX#cityY#substanceY#
I thought to make it this way, but it seems like it pushes always in the same array of objects. If I put oggetto = {values: arrayDateValue, key: key}; inside the d3.csv function, instead if I put outside the function it add me only empty objects.
Here is my code:
var final = new Array();
var oggetto;
var key;
function creaDati() {
var newdate;
var arrayDateValue = new Array();
var selString = aggiungiElemento().split("#");
//selString is an array with selString[0]: city, selString[1]: substance and so on..
var citySelected = "";
var substanceSelected = "";
for (var i = 0; i < selString.length - 1; i++) {
if (i % 2 === 0) {
citySelected = selString[i];
} else if (i % 2 !== 0) {
substanceSelected = selString[i];
key = citySelected + "#" + substanceSelected;
d3.csv("/CSV/" + citySelected + ".csv", function(error, dataset) {
dataset.forEach(function(d) {
arrayDateValue.push({
x: d.newdate,
y: d[substanceSelected]
});
});
});
oggetto = {
values: arrayDateValue,
key: key
};
arrayDateValue = [];
final.push(oggetto);
}
}
}
Any idea ?
First you should make the if statement for the city and then for the key, which you seem to be doing wrong since you want the pair indexes to be the keys and the not pair to be the city, and you are doing the opposite. And then you need to have the d3.csv and push the objects outside of the if statement, otherwise in your case you are just adding elements with citySelected="".
Try something like :
for(var i = 0; i < selString.length -1; i+=2){
cittySelected = selString[i];
substanceSelected = selString[i+1];
key = citySelected + "#" + substanceSelected;
d3.csv("/CSV/"+citySelected+".csv", function(error, dataset){
dataset.forEach(function(d){
arrayDateValue.push({x: d.newdate, y: d[substanceSelected]});
});
});
oggetto = {values: arrayDateValue, key: key};
arrayDateValue = [];
final.push(oggetto);
}
It's is not the best way to do it, but it is clearer that what you are following, i think.
In the if(i % 2 == 0) { citySelected = ... } and else if(i % 2 !== 0) { substanceSelected = ... } citySelected and substanceSelected will never come together.
The values should be in one statement:
if(...) { citySelected = ...; substanceSelected = ...; }
The string can be splitted into pairs
city1#substance1, city2#substance2, ...
with a regex (\w{1,}#\w{1,}#).
Empty the arrayDateValue after the if-statement.
Hint:
var str = "cityX#substanceX#cityY#substanceY#";
function createArr(str) {
var obj = {};
var result = [];
var key = "";
// '', cityX#substanceX, '', cityYsubstanceY
var pairs = str.split(/(\w{1,}#\w{1,}#)/g);
for (var i = 0; i < pairs.length; i++) {
if(i % 2 !== 0) {
key = pairs[i];
// d3 stuff to create values
obj = {
// Values created with d3 placeholder
values: [{x: "x", y: "y"}],
// Pair
key: key
};
result.push(obj);
}
// Here should be values = [];
}
return result;
}
var r = createArr(str);
console.log(r);
May be you can do like this;
var str = "cityX#substanceX#cityY#substanceY",
arr = str.split("#").reduce((p,c,i,a) => i%2 === 0 ? p.concat({city:c, key:a[i+1]}) : p,[]);
console.log(JSON.stringify(arr));
RESOLVED-
The problem is about d3.csv which is a asynchronous function, it add in the array when it finish to run all the other code.
I make an XMLHttpRequest for each csv file and it works.
Hope it helps.

JavaScript module pattern gives unexpected results

I am just messing around with generating random human names in JS. I wanted to also practice using the module pattern but I can't get my function to return a normal array.
What I want to save is how often a letter (or set of letters) shows up after another letter.
So with 'jacob' and 'jarod' I should see that the letter 'a' came after the letter 'j' 2 times like this: myArray[j][a] //2
BUT what I have instead somehow turned the array into a set of properties and to figure out that 'a' comes up 2 times I have to check it this way : myArray.j.a //2
can someone explain why this is and how I can fix it?
var names = ['jacob', 'cameron', 'zach', 'lake', 'zander', 'casey', 'carl', 'jeff', 'jack', 'jarod', 'max', 'cat', 'mallory', 'dana', 'hannah', 'stu', 'abrham', 'isaac'];
var probabilities = (function(){
var nextLetterProbability = [];
function addProbability(index, letters){
if(nextLetterProbability[index] !== undefined){
if(nextLetterProbability[index][letters] !== undefined){
nextLetterProbability[index][letters] = nextLetterProbability[index][letters] + 1;
}
else
nextLetterProbability[index][letters] = 1;
}
else{
nextLetterProbability[index] = [];
nextLetterProbability[index][letters] = 1;
}
}
return {
learn:function(names, chainLength){
for (var i = 0; i < names.length; i++) {
var name = names[i];
for (var j = 0; j < name.length - chainLength; j++) {
var start = name[j];
var next = name.slice(j + 1, j + chainLength + 1)
addProbability(start, next);
};
};
},
getLearnedArray:function(){
return nextLetterProbability;
}
}
})();
var nextLetterProbability = []; needed to be var nextLetterProbability = {}; because it is an associative array and is handled as an object.

Javascript: attach child several deep to object?

If I want to iterate through a list like this:
var inputArray = [
'CHILD0',
'PARENT0_CHILD1',
'PARENT1_PARENT2_CHILD2',
'PARENT1_PARENT3_CHILD3',
'PARENT1_PARENT3_CHILD4'
];
And have it return an object like so:
var resultObject = {
CHILD0: null,
PARENT0: {CHILD1: null},
PARENT1: {
PARENT2: {CHILD2: null},
PARENT3: {
CHILD3: null,
CHILD4: null
}
}
};
How could I iterate through the array to return the result?
I've got something like this:
function iterateArray (inputArray) {
var _RESULT = {};
for (var i = 0; i < inputArray.length; i += 1) {
var _inputName = inputArray[i];
var _inputNameArray = _input.split('_');
var _ref;
for (var n = 0; n < _inputNameArray.length; n += 1) {
//...?
}
_RESULT[_ref] = null;
}
return _RESULT;
}
var resultObject = iterateArray(inputArray);
Not sure what to do from this point. Think I might need a recursive function of sorts. Thoughts?
With minimal changes to your code:
function iterateArray (inputArray) {
var _RESULT = {};
for (var i = 0; i < inputArray.length; i += 1) {
var _inputName = inputArray[i];
var _inputNameArray = _inputName.split('_');
var _ref = _RESULT;
for (var n = 0; n < _inputNameArray.length - 1; n += 1) {
if (!_ref[_inputNameArray[n]]) _ref[_inputNameArray[n]] = {};
_ref = _ref[_inputNameArray[n]];
}
_ref[_inputNameArray[n]] = null;
}
return _RESULT;
}
You never need recursion, as it can always be unwrapped into iteration (and vice versa). Things are just sometimes much nicer one way or another.
EDIT: What's with all the underscores? :)
EDIT2: The key point to understanding this is reference sharing. For example:
For CHILD0, _ref = _RESULT means both of the variables are pointing at the same {}. When you do _ref['CHILD0'] = null, it is the same as doing _RESULT['CHILD0'] = null.
For PARENT0_CHILD1, first _ref = _RESULT as above, so _ref['PARENT0'] = {} is the same as _RESULT['PARENT0'] = {}. Then we switch the meaning of _ref to be the same thing as _RESULT['PARENT0']; when we assign _ref['CHILD1'] = null, it is the same as assigning _RESULT['PARENT0']['CHILD1'] = null.

Joining two collections efficiently?

I have run into an issue where I am trying to join two arrays similar to the ones below:
var participants = [
{id: 1, name: "abe"},
{id:2, name:"joe"}
];
var results = [
[
{question: 6, participantId: 1, answer:"test1"},
{question: 6, participantId: 2, answer:"test2"}
],
[
{question: 7, participantId: 1, answer:"test1"},
{question: 7, participantId: 2, answer:"test2"}
]
];
Using nested loops:
_.each(participants, function(participant) {
var row, rowIndex;
row = [];
var rowIndex = 2
return _.each(results, function(result) {
return _.each(result, function(subResult) {
var data;
data = _.find(subResult, function(part) {
return part.participantId === participant.id;
});
row[rowIndex] = data.answer;
return rowIndex++;
});
});
});
This works ok as long as the arrays are small, but once they get larger I am getting huge performance problems. Is there a faster way to combine two arrays in this way?
This is a slimmed down version of my real dataset/code. Please let me know if anything doesn't make sense.
FYI
My end goal is to create a collection of rows for each participant containing their answers. Something like:
[
["abe","test1","test1"],
["joe","test2","test2"]
]
The perf* is not from the for loops so you can change them to _ iteration if they gross you out
var o = Object.create(null);
for( var i = 0, len = participants.length; i < len; ++i ) {
o[participants[i].id] = [participants[i].name];
}
for( var i = 0, len = results.length; i < len; ++i ) {
var innerResult = results[i];
for( var j = 0, len2 = innerResult.length; j < len2; ++j) {
o[innerResult[j].participantId].push(innerResult[j].answer);
}
}
//The rows are in o but you can get an array of course if you want:
var result = [];
for( var key in o ) {
result.push(o[key]);
}
*Well if _ uses native .forEach then that's easily order of magnitude slower than for loop but still your problem is 4 nested loops right now so you might not even need the additional 10x after fixing that.
Here is a solution using ECMA5 methods
Javascript
var makeRows1 = (function () {
"use strict";
function reduceParticipants(previous, participant) {
previous[participant.id] = [participant.name];
return previous;
}
function reduceResult(previous, subResult) {
previous[subResult.participantId].push(subResult.answer);
return previous;
}
function filterParticipants(participant) {
return participant;
}
return function (participants, results) {
var row = participants.reduce(reduceParticipants, []);
results.forEach(function (result) {
result.reduce(reduceResult, row);
});
return row.filter(filterParticipants);
};
}());
This will not be as fast as using raw for loops, like #Esailija answer, but it's not as slow as you may think. It's certainly faster than using Underscore, like your example or the answer given by #Maroshii
Anyway, here is a jsFiddle of all three answers that demonstrates that they all give the same result. It uses quite a large data set, I don't know it compares to the size you are using. The data is generated with the following:
Javascript
function makeName() {
var text = "",
possible = "abcdefghijklmnopqrstuvwxy",
i;
for (i = 0; i < 5; i += 1) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
var count,
count2,
index,
index2,
participants = [],
results = [];
for (index = 0, count = 1000; index < count; index += 4) {
participants.push({
id: index,
name: makeName()
});
}
for (index = 0, count = 1000; index < count; index += 1) {
results[index] = [];
for (index2 = 0, count2 = participants.length; index2 < count2; index2 += 1) {
results[index].push({
question: index,
participantId: participants[index2].id,
answer: "test" + index
});
}
}
Finally, we have a jsperf that compares these three methods, run on the generated data set.
Haven't tested it with large amounts of data but here's an approach:
var groups = _.groupBy(_.flatten(results),'participantId');
var result =_.reduce(groups,function(memo,group) {
var user = _.find(participants,function(p) { return p.id === group[0].participantId; });
var arr = _.pluck(group,'answer');
arr.unshift(user.name);
memo.push(arr);
return memo ;
},[]);
The amounts of groups would be the amount of arrays that you'll have so then iterating over that with not grow exponentially as if you call _.each(_.each(_.each which can be quite expensive.
Again, should be tested.

String split and count the number of occurrences and also

I have a string
var stringIHave = "Java$$Java$$jQuery$$Java$$jQuery$$Java$$Java$$Java$$Hibernate$$Java$$Java$$Spring$$Instagram$$jQuery$$jQuery$$";
How to get the count of the number of occurrences of each entry, The occurrence I get, is from a JSON like Java = 8 and etc...
First of all you need to split your srting to array:
var keywordsArr = stringIHave.split( '$$' );
then you need to have an object for example to store counts:
var occur = {};
and then just create simple for loop to count all occurrences:
for( var i = 0; i < keywordsArr.length; i++ ) {
occur[ keywordsArr[ i ] ] = ( occur[ keywordsArr[ i ] ] || 0 ) + 1;
}
now your object occur will have names as keys and count as values.
See jsFiddle demo.
Also as you have at end of your string $$ you maybe will need to remove last item from keywordsArr so just do after split function call:
keywordsArr.pop();
See demo without last element.
So final code will be like:
var stringIHave = "Java$$Java$$jQuery$$Java$$jQuery$$Java$$Java$$Java$$Hibernate$$Java$$Java$$Spring$$Instagram$$jQuery$$jQuery$$",
keywordsArr = stringIHave.split( '$$' ),
occur = {};
keywordsArr.pop();
for( var i = 0; i < keywordsArr.length; i++ ) {
occur[ keywordsArr[ i ] ] = ( occur[ keywordsArr[ i ] ] || 0 ) + 1;
}
for( var key in occur ) {
document.write( key + ' - ' + occur[key] + '<br/>' );
} ​
I'd suggest the following:
function stringCount(haystack, needle) {
if (!needle || !haystack) {
return false;
}
else {
var words = haystack.split(needle),
count = {};
for (var i = 0, len = words.length; i < len; i++) {
if (count.hasOwnProperty(words[i])) {
count[words[i]] = parseInt(count[words[i]], 10) + 1;
}
else {
count[words[i]] = 1;
}
}
return count;
}
}
console.log(stringCount("Java$$Java$$jQuery$$Java$$jQuery$$Java$$Java$$Java$$Hibernate$$Java$$Java$$Spring$$Instagram$$jQuery$$jQuery$$", '$$'));
​
JS Fiddle demo.
References:
Object.hasOwnProperty().
parseInt().
String.split().
It's not entirely clear what final objective is. Following creates an object from string that looks like
Object created:
{
"Java": 8,
"jQuery": 4,
"Hibernate": 1,
"Spring": 1,
"Instagram": 1
}
JS:
var str = 'Java$$Java$$jQuery$$Java$$jQuery$$Java$$Java$$Java$$Hibernate$$Java$$Java$$Spring$$Instagram$$jQuery$$jQuery$$';
var arr = str.split('$$')
var obj = {};
for (i = 0; i < arr.length; i++) {
if (arr[i] != '') {
if (!obj[arr[i]]) {
obj[arr[i]] = 0;
}
obj[arr[i]]++;
}
}
You can loop over the object to get all values or simply look up one value
var jQueryOccurences= obj['jQuery'];
DEMO: http://jsfiddle.net/25hBV/1/
Now a days you can do
const str = "Java$$Java$$jQuery$$Java$$jQuery$$Java$$Java$$Java$$Hibernate$$Java$$Java$$Spring$$Instagram$$jQuery$$jQuery$$";
var result = str.split("$$").reduce(function(acc, curr) {
curr && (acc[curr] = (acc[curr] + 1) || 1);
return acc
}, {});
console.log(result);
Split the string into an array, and putting the array into an object takes care of duplicates and counts occurences as key/value pairs in the object, see fiddle!
var stringIHave = "Java$$Java$$jQuery$$Java$$jQuery$$Java$$Java$$Java$$Hibernate$$Java$$Java$$Spring$$Instagram$$jQuery$$jQuery$$",
s = stringIHave.split('$$');
obj = {};
for (var i=s.length; i--;) {
obj[s[i]] = (s[i] in obj) ? obj[s[i]]+1 : 1;
}
// obj.Java == 8
FIDDLE
If you want it short and sweet:
// variable declarations
var arParts = stringIHave.match(/\w+/g),
result = {},
i = 0,
item;
// Copy the array to result object
while (item = arParts[i++]) result[item] = (result[item] || 0 ) + 1;
demo

Categories

Resources