How to most efficiently generate string from array of objects in javascript? - javascript

I have the following:
var students = [{name:"Jordan", age:"6"},{name:"Jake", age:"7"},{name:"Mark", age:"10"}]
I want to generate a string like this:
"Jordan,6|Jake,7|Mark,10"
What is the most efficient way to do this?
I am currently using:
var studentstr = "";
for(var i = 0; i < students.length; i++) {
studentstr = students['name'] + "," + students['age'] + "|"
}
studentstr = studentstr.substring(0, studentstr.length - 1);
Also, performance-wise, if I had an array of 2,000 items, is it "costly" to perform this transformation? The resulting string contains both keys in the object and not a single join on one object in the property.

You can map each student object to a string and then join them all with |:
var studentstr = students.map(function (student) {
return student.name + ',' + student.age;
}).join('|');
Also, performance-wise, if I had an array of 2,000 items, is it "costly" to perform this transformation?
No.

Yes, using string concatenation in a loop is costly. The string grows for each iteration, and each time you have to copy the entire previous string to create the new version. The execution time of the loop grows exponentially to the number of items.
You can put the string for each object in an array, then join them together:
var students = [{name:"Jordan", age:"6"},{name:"Jake", age:"7"},{name:"Mark", age:"10"}];
var items = [];
for (var i = 0; i < students.length; i++) {
items.push(students[i].name + ',' +students[i].age);
}
var str = items.join('|');
// display result in snippet
document.write(str);

map works well for this:
var students = [{name:"Jordan", age:"6"},{name:"Jake", age:"7"},{name:"Mark", age:"10"}];
var result = students.map(function(student) {
return student.name + ',' + student.age;
});
alert(result.join('|'));

Try this and see your console:
var string = '';
for (var s in students) {
string += students[s].name + ', ' + students[s].age + ' | ';
}
console.log(string);
Fiddle: http://jsfiddle.net/80ss0u14/
I do not think it is costly to go on with such approach. It may be the most efficient way to iterate through the data.

Related

Print the number of values as take from the Index value from array

Recently Attended the interview, Some one asked the question like below:
var array = [0,1,2,3,4,5];
Output :
temp:
temp1:1
temp22:22
temp333:333
temp4444:4444
temp55555:55555
I tried below code it is working fine but is there any best solution for this example :
array.forEach(function(item,index){
var text ="";
if(index >= 2){
for(var j =1; j <= index; j++){
text += index;
}
console.log("temp"+text + ":" + text);
}else{
console.log("temp"+index + ":" + index);
}
});
Thanks in advance!
Using ES6 template strings and String.prototype.repeat
var array = [0,1,2,3,4,5];
array.forEach(item => {
const text = String(item).repeat(item);
console.log(`temp${text}: ${text}`);
})
And the same code translated into ES5 - this will work in all browsers starting from IE9 and above.
var array = [0,1,2,3,4,5];
array.forEach(function(item) {
var text = Array(item+1).join(item);
console.log("temp" + text + ": " + text);
})
Since String.prototype.repeat does not exist in ES5, there is a bit of a hack to generate a string of specific length with repeating characters:
Array(initialCapacity) will create a new array with empty slots equal to what number you pass in, Array.prototype.join can then be used to concatenate all members of the array into a string. The parameter .join takes is the separator you want, so, for example you can do something like this
var joinedArray = ["a","b","c"].join(" | ");
console.log(joinedArray);
However, in this case, each of the members of the array is blank, since the array only has blank slots. So, upon joining, you will get a blank string, unless you specify a separator. You can leverage that to get a repeat functionality, as you are essentially doing something like this
//these produce the same result
var repeatedA = ["","",""].join("a");
var repeatedB = Array(3).join("b");
console.log("'a' repeated:", repeatedA);
console.log("'b' repeated:", repeatedB);
Using the Array function, you can scale it to any number of repeats you want. The only trick is that you need to add 1 when creating the array, since you get one less character when joining.
You could iterate the array and iterate the count. Then display the new string.
var array = [0, 1, 2, 3, 4, 5];
array.forEach(function (a, i) {
var s = '';
while (i--) {
s += a;
}
console.log ('temp' + s + ':' + s);
});

How to iterate through an array containing objects - javascript

I have an array containing objects that looks like this:
[{\"user\":\"mcnewsmcfc\",\"num\":11},{\"user\":\"ManCityFNH\",\"num\":7}];
I am then using:
var jsonu = JSON.parse(tweets.replace(/"/g, '\"'));
to remove all the unwanted characters from the array. My question is then how to iterate through the array and (EDIT) use the values of "user" and "num" for each object in the table (EDIT).
This is what I initally have but this does not extract the correct values:
for (var u in jsonu) {
var row = $('<row></row>');
row.append('<th>' + jsonu[u][0] + '</th><td>' + jsonu[u][1] + '</td>');
$('#userTable').append(row);
}
var tweets = '[{\"user\":\"mcnewsmcfc\",\"num\":11},{\"user\":\"ManCityFNH\",\"num\":7}]';
var jsonu = JSON.parse(tweets.replace(/"/g, '\"'));
for (var u in jsonu) {
var row = $('<row></row>');
row.append('<th>' + jsonu[u].user + '</th><td>' + jsonu[u].num + '</td>');
$('#userTable').append(row);
}
since jsonu is an array, u is just the index in the array. jsonu[u] will return back the object at that index in the array, which is a javascript object.
So to access the user and num property, simply call jsonu[u].user and jsonu[u].num

Create array based on instance of delimiter/square-brackets

I have a string and I wanna create an array with even occurrence of "[]"
"Match[0][a][5][b][0][d][2]"
I want to split them and make an array using this string on the basis of instance of "[]". Each element of the array must have 2 occurrence of "[]" and the next element has two more occurrence of"[]". In another words I wanna create an array with even occurrence of "[]"
I want to make an array from string like:
["Match[0]['a']", "Match[0]['a'][5]['b']", "Match[0]['a'][5]['b'][0]['d']"]
Using javascript/jQuery
I have tried match but I only got it as far as this.
// ['part1.abc', 'part2.abc', 'part3.abc', 'part4']
'part1.abc.part2.abc.part3.abc.part4'.match(/[^.]+(\.[^.]+)?/g);
You can get the individual pieces in your array and then manipulate the result until it has the form you want. An example could be this one:
var str = "Match[0][a][5][b][0][d][2]";
var result = [];
str.split(/[\]\[]{1,2}/).slice(0,-1).reduce(function(acc,item, index) {
acc += '[' + (isNaN(item) ? "'" + item + "'" : item) + ']';
if (index %2 === 0 && index !== 0) {
result.push(acc);
}
return acc;
});
console.log(result) // ["Match[0]['a']", "Match[0]['a'][5]['b']", "Match[0]['a'][5]['b'][0]['d']"]
You can get each bracket with match(/\[.\]/g) and then composes your arrays by adding two by two.
var matches = "Match[0][a][5][b][0][d][2]".match(/\[(.)\]/g);
var result = [];
for (var i = 0; i < matches.length; i += 2) {
var brackets = '';
for(var j = 0; j< i; j++) {
brackets += matches[j];
}
result.push("Match" + brackets);
}
result.shift();
Wow its fun :) ... trying api and see how everyone is solving it. This is what i tried see if this is helpful.
str = "STR[1][3][4d][re]"
var re=/\[\w+\]/g;
var mat = str.match(re);
var ar = [];
for(i=2; i<= mat.length; i=i+2){
ar[ar.length] = "STR" + mat.slice(0,i).join("")
}
console.dir(ar)

jQuery: Extract array

I have a varcontains:
var flags = {USA, Brazil, Germany, Canada};
I can get values with number of each key
http://jsfiddle.net/YQSHr/
How to get numbers {1, 2, 3} without setting them in the var and starting from 1
var flags = {USA, Canada, Germany};
Edit 2:
Also I have another var without ,
var flags = 'USA Brazil Germany Canada';
Use
var flags = ['USA','Brazil','Germany','Canada'];
Then you can iterate over it with
$.each(flags, function(key, value){
var yourkey = key + 1; // Because you want 1 indexed
}
If you want an array of strings, you will need to use square brackets:
var flags = ["USA", "Canada", "Germany"];
/* or
var flags = 'USA Brazil Germany Canada'.split(' ');
*/
Yet for getting the numbers from the indices you will need to add 1, since the array indices are zero-based:
$.each(flags, function(index, value){
$('#flags').append('<span>' + value + (index+1) + '</span> ')
});
Output:
USA1
Canada2
Germany3
var flags = ['USA', 'Canada', 'Germany'];
$.each(flags, function(i, country){
$('#flags').append('<span>' + country + (i += 1) + '</span> ')
});
http://jsfiddle.net/ethagnawl/YQSHr/3/
var flags = ['USA', 'Canada', 'Germany'];
$.each(flags, function(key, value){
$('#flags').append('<span>' + (key+1) + ' '+ value + '</span> ')
});
Set an array with strings
DEMO VIEW
Your code is not valid.
var flags = {USA, Brazil, Germany, Canada};//error
Please look up how to use objects or arrays and choose one instead of a mix. This will solve the issue you are having. As others have pointed out in the answers, you will be able to use an array of strings to match with an index, or use indexes in an object to match with the strings.
This would basically mean changing flags to
var flags = ["USA","Brazil","Germany","Canada"];
http://jsfiddle.net/YQSHr/6/
However, depending on how many flags you are using you may want to use a data structure.
var flagHolder = (function(){
var flags = [];
var flagIndex = 0;
function addFlag(name){
var flag = {};
flag.name = name;
flag.index = flagIndex++;
flags.push(flag);
return flag.index;
}
function getFlag(index){
return flags[index];
}
function getAllFlags(){
return flags;
}
return {
getAllFlags: getAllFlags,
getFlag: getFlag,
addFlag: addFlag
};
})();
Which could be used like this:
var USA = flagHolder.addFlag("USA");
var Canada = flagHolder.addFlag("Canada");
var Germany = flagHolder.addFlag("Germany");
var Brazil = flagHolder.addFlag("Brazil");
//Get Single
$("#flag").html(flagHolder.getFlag(USA).name);
//Get All
$.each(flagHolder.getAllFlags(), function(key,value){
$('#flags').append('<span>' + (key+1) + '</span> ');
});
Here is a demo for that: http://jsfiddle.net/YQSHr/7/

Append number to a comma separated list

the list looks like:
3434,346,1,6,46
How can I append a number to it with javascript, but only if it doesn't already exist in it?
Assuming your initial value is a string (you didn't say).
var listOfNumbers = '3434,346,1,6,46', add = 34332;
var numbers = listOfNumbers.split(',');
if(numbers.indexOf(add)!=-1) {
numbers.push(add);
}
listOfNumbers = numbers.join(',');
Basically i convert the string into an array, check the existence of the value using indexOf(), adding only if it doesn't exist.
I then convert the value back to a string using join.
If that is a string, you can use the .split() and .join() functions, as well as .push():
var data = '3434,346,1,6,46';
var arr = data.split(',');
var add = newInt;
arr.push(newInt);
data = arr.join(',');
If that is already an array, you can just use .push():
var data = [3434,346,1,6,46];
var add = newInt;
data.push(add);
UPDATE: Didn't read the last line to check for duplicates, the best approach I can think of is a loop:
var data = [3434,346,1,6,46];
var add = newInt;
var exists = false;
for (var i = 0; i < input.length; i++) {
if (data[i] == add) {
exists = true;
break;
}
}
if (!exists) {
data.push(add);
// then you would join if you wanted a string
}
You can also use a regular expression:
function appendConditional(s, n) {
var re = new RegExp('(^|\\b)' + n + '(\\b|$)');
if (!re.test(s)) {
return s + (s.length? ',' : '') + n;
}
return s;
}
var nums = '3434,346,1,6,46'
alert( appendConditional(nums, '12') ); // '3434,346,1,6,46,12'
alert( appendConditional(nums, '6') ); // '3434,346,1,6,46'
Oh, since some really like ternary operators and obfustically short code:
function appendConditional(s, n) {
var re = new RegExp('(^|\\b)' + n + '(\\b|$)');
return s + (re.test(s)? '' : (''+s? ',':'') + n );
}
No jQuery, "shims" or cross-browser issues. :-)

Categories

Resources