jQuery: Extract array - javascript

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/

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 most efficiently generate string from array of objects in 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.

Formatting a JS array into specific string

I have a Javascript array
var arr = ['[dim].[att].&[123]','[dim].[att5].&[123]','[dim4].[att].&[123]','[dim3].[att].&[123]','[dim].[att].&[222]']
from this array I need to produce output like this:
var str = " 'dim'[att] = 123 || 'dim'[att] = 222 , 'dim'[att5] = 123 , 'dim4'[att] = 123 , 'dim3'[att] = 123 ";.
I first need to split each value in the array by .& and then I need to group all the items by index 0 of the resultant array. So in this case I will group [dim].[att].&[123] & [dim].[att].&[222] becuase of [dim].[att]
From each of these items, now I need to split by ]. and produce requires output such that [dim].[att].&[123] becomes 'dim'[att] = 123
I do not want to use multiple for loops for this purpose. I already have that solution ready. So far i am able to group the items, but not sure how to generate required output. Check this fiddle for my solution
You just need to use Array.map and Array.join
var str = arr.map(function(s){
var a = s.match(/\w+/g);
return "'" + a[0] + "'[" + a[1] + "] = " + a[2];
}).join("||");
In the above, we are taking the three parts which we want into an Array using s.match(/\w+/g) and then returning in the format we want.
Also, at last, Array.join is called with || as the String
DEMO
I was looking for this; Code below and DEMO
var arr = ['[dim].[att].&[123]', '[dim].[att5].&[123]', '[dim4].[att].&[123]', '[dim3].[att].&[123]', '[dim].[att].&[222]']
var res = _.chain(arr)
.groupBy(function (x) {
return x.match(/.+?\.&/i)[0];
})
.map(function(y) {
return _.map(y, function (z) {
var a = z.match(/\w+/g);
return "'" + a[0] + "'[" + a[1] + "] = " + a[2];
}).join(" || ");
})
.value().join(", ");
console.log(res)

Count occurrence times of each character in string

I have a string like this:
(apple,apple,orange,banana,strawberry,strawberry,strawberry). I want to count the number of occurrences for each of the characters, e.g. banana (1) apple(2) and strawberry(3). how can I do this?
The closest i could find was something like, which i dont know how to adapt for my needs:
function countOcurrences(str, value){
var regExp = new RegExp(value, "gi");
return str.match(regExp) ? str.match(regExp).length : 0;
}
Here is the easiest way to achieve that by using arrays.. without any expressions or stuff. Code is fairly simple and self explanatory along with comments:
var str = "apple,apple,orange,banana,strawberry,strawberry,strawberry";
var arr = str.split(','); //getting the array of all fruits
var counts = {}; //this array will contain count of each element at it's specific position, counts['apples']
arr.forEach(function(x) { counts[x] = (counts[x] || 0)+1; }); //checking and addition logic.. e.g. counts['apples']+1
alert("Apples: " + counts['apple']);
alert("Oranges: " + counts['orange']);
alert("Banana: " + counts['banana']);
alert("Strawberry: " + counts['strawberry']);
See the DEMO here
You can try
var wordCounts = str.split(",").reduce(function(result, word){
result[word] = (result[word] || 0) + 1;
return result;
}, {});
wordCounts will be a hash {"apple":2, "orange":1, ...}
You can print it as the format you like.
See the DEMO http://repl.it/YCO/10
You can use split also:
function getCount(str,d) {
return str.split(d).length - 1;
}
getCount("fat math cat", "at"); // return 3

want to get textbox value

I have two textboxes which values are like:
312,315
315,313
I want to get a string with all the values, for example: 312,315,313 skipping existing values in both fields.
My code:
var firstbox = $("#firstbox").val();
var secondbox = $("#secondbox").val();
var newvalue = $(firstbox).not(secondbox).get();
console.log(newvalue);
But it's not working, how can I get my desired output using JQuery?
thanks.
You could concatenate the two, joining them with a comma.
You would then have a comma delimited string, so you could split at the comma, remove any duplicate values, then rejoin the remaining values.
Something like this:
var firstbox = $("#firstbox").val(),
secondbox = $("#secondbox").val(),
boxes = firstbox + "," + secondbox,
arr = boxes.split(","),
res = [];
$.each(arr, function(i, el){
if($.inArray(el, res) === -1){
res.push(el);
}
});
$("#res").html(res.join(",").replace(/(^,)|(,$)/g, ""));
Fiddle
Maybe this will give you a hint in the right direction:
// get comma seperated list of all values
var allValues = $('#firstbox').val() + ',' + $('#secondbox').val();
// make an array out of them
var allValuesArray = allValues.split(',');
// sort out repeated values
// by creating a new array 'distinctValues'
var distinctValues = [],
currentValue,
valuesLookup = {};
for (var i = allValuesArray.length - 1; i >= 0; i--) {
currentValue = allValuesArray[i];
if (!valuesLookup[currentValue]) {
valuesLookup[currentValue] = true;
distinctValues.push(currentValue);
}
}
// output the result to the console
console.log(distinctValues.join(','));

Categories

Resources