Include array index when using Array.join() - javascript

I am trying to add index of an array element when converting an Array into a string. Here is my code
var arr = ["a", "b", "c", "d", "e"];
console.log(arr.join('')); // Will log "abcdef"
But my required output is a0b1c2d3e4.
If I write like below, I will get the result
var str = "";
for(var i = 0, l = arr.length; i++){
str += (arr[i] + i);
}
console.log(str);
But I would like to know if any trick is there with Array.join()

You can use Array.prototype.map for it, see here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
arr.map(function(val, index) { return val + index.toString(); }).join("");

Related

nested for each loop to insert value which in array without duplication and loop start from first

Example
If my values are in array like this
var myPlaces = ["a", "b", "c"];
var friendPlaces = ["d", "0", "e"];
for(var i = 0; i < myPlaces.length; i++) {
console.log(myPlaces[i]);
for(var j = 0; j < friendPlaces.length; j++) {
if (myPlaces[i] == friendPlaces[i]) {
console.log(myPlaces[i]);
};
I need answer as
(a,d)(b,0)(c,e) as three result but it gives count more than 3
help me to modify my current answer (a,d) (d,a) (d,b) (d,c) then (b,o)
You can use Array#map (Assuming your input arrays are of same length with fixed count of arrays- i.e. 2 in your case).
If you use map on myPlaces then 1st parameter is current value of myPlaces in loop and the 2nd parameter is index of that element in array. So you can match current element in myPlaces with elements from friendPlaces array with the same index using this index.
var myPlaces = ["a", "b", "c"];
var friendPlaces = ["d", "0", "e"];
var result = myPlaces.map((e, i) => "("+e +","+ friendPlaces[i]+")");
console.log(result);

Show array element on button click using javascript

I have an array of strings, you can see below and i want to alert each element one by one on button click:
function mysimplefunc() {
var i = 0;
var array = ["a", "b", "c", "d"];
if (array.length < 4)
{
var str = array[i];
i++;
alert(str);
}
}
below is asp code:
<asp:Button ID="btn_SHow" runat="server" Text="Show Elements" OnClientClick="mysimplefunc();" />
But its not working.
the if loop will not working since array length is 4
and u must use for loop inorder to iterate each element..!!
for ( i=0;i<array.length;i++)
{
var str = array[i];
alert(str);
}
Try this function. This handles creating the array counter (i) as a global variable, and any number of items can be included in the array, not just four.
function mysimplefunc() {
var array = ["a", "b", "c", "d"];
if (typeof i == "undefined") {i = 0};
alert(array[i++]);
if (i == array.length) {i = 0}
}
function mysimplefunc() {
var i = 0; //declare & initialise a integer variable used for loop counter.
var array = ["a", "b", "c", "d"]; //Create an string array of 4 elements with name array
var arrLength=array.length; //find the length of array elements
for (;i<arrLength;) //iterate over the array elements upto last element
{
var str = array[i]; //take first element from array
i++; //increment the loop counter
alert(str);//popup the small window with values present in array
}
}

Convert array to space-delimited string, while joining individual values

I have a multiple select box on my page. I can get the values of all the selected child options in jQuery easily like this:
$("#select").val();
That gives me an array like this:
["Hello", "Test", "Multiple Words"]
Now, I want to convert this array into a space-delimited string, but also join the individual words in each value with a dash, so that I end up with this:
"Hello Test Multiple-Words"
How would I go about doing that?
var values = $("#select").val();
for (var i = 0; i < values.length; ++i) {
values[i] = values[i].replace(" ", "-");
}
var spaceDelimitedString = values.join(" ");
var result = $.map($("#select").val() || [], function (x) {
return x.replace(/\s/g, '-');
}).join(' ');
If Multiple-Words can be as Multiple Words, then you can simply use .join and get the final output as "Hello Test Multiple Words".
If not, you can write a loop like below to get the result.
var myList = ["Hello", "Test", "Multiple Words"];
var result = '';
for (var i = 0; i < myList.length; i++) {
result += myList[i].replace(/\s/g, '-') + ' ';
}
DEMO: http://jsfiddle.net/bmXk5/
Here a simple one liner with Array.map:
var arr = ["Hello", "Test", "Multiple Words"];
arr.map(function(val) { return val.replace(' ', '-') }).join(' ');
var vals = ["Hello", "Test", "Multiple Words"];
var result = $.map(vals, function(str){ return str.replace(/\s/g, '-') })
.join(' ');
This should do the job for you.
function combineWords(arr) {
var i, l;
for(i = 0, l = arr.length; i < l; i++) {
arr[i] = arr[i].replace(' ', '-') ;
}
return arr;
}

How might I return multiple arrays with equal values from a larger array with mixed values?

I have an array that after being sorted appears like this:
var arr = ["a", "a", "b", "b", "b", "b", "c", "c", "c"];
There are 2 "a" Strings, 4 "b" Strings, and 3 "c" Strings.
I am trying to return 3 separate arrays, returning them one at a time from a loop, containing only matching values. So, upon the first iteration, the returned array would appear as newArr = ["a", "a"], the second as newArr = ["b", "b", "b", "b"] and on the third iteration as newArr = ["c", "c", "c"].
However, this is a small array of predefined values, and I need an algorithm that can perform the same operation on an array of unknown size, unknown elements, and with an unknown number of like elements. (and keep in mind that the array is already sorted to begin with, in this context)
Here's my crazy code that is displaying some unusual, and incorrect, results:
var arr = ["a", "a", "b", "b", "b", "b", "c", "c", "c"];
for(var index = 0; index < arr.length; index++)
{
var test = "";
var newArr = []; // resets the new array upon each iteration
var str = arr[index]; // initialized as the next unique index-value
for(var i = index; i < arr.length; i++)
{
if(arr[i] == str)
{
newArr.push(arr[k]);
test += arr[i] + " ";
}
else
{
index = i; // changing the outer loop variable
break; // exiting the inner loop
}
} // end of inner loop
window.alert(test);
setValues(newArr);
} // end of outer loop
function setValues(arrSorted)
{
var here = document.getElementById("here");
for(var i = 0; i < arrSorted.length; i++)
{
here.innerHTML += arrSorted[i] + " ";
}
here.innerHTML += "<br />";
} // end of setValues function
var arr = ["a", "a", "b", "b", "b", "b", "c", "c", "c"];
var arrays = {};
for (var i=0;i<arr.length;i++) {
if (!arrays[arr[i]]) arrays[arr[i]] = [];
arrays[arr[i]].push(arr[i]);
}
this will give you the equivalent of
arrays = {};
arrays['a'] = ['a','a'];
arrays['b'] = ['b','b','b','b','b'];
arrays['c'] = ['c','c','c'];
You can use a function like this to divide the array into several arrays:
function divide(arr) {
var subArrays = [];
var current = null;
var subArray = null;
for (var i = 0; i < arr.length; i++) {
if (arr[i] != current) {
if (subArray != null) subArrays.push(subArray);
current = arr[i];
subArray = [];
}
subArray.push(arr[i]);
}
if (subArray != null) subArrays.push(subArray);
return subArrays;
}
Demo: http://jsfiddle.net/Guffa/d8CBD/
This is how I would do it:
var arr = ["a", "a", "b", "b", "b", "b", "c", "c", "c"];
var out = [], prev;
for (var i = 0, j = 0, len = arr.length; i < len; i++) {
if (arr[i] !== prev || !out.length) {
out[j++] = [prev = arr[i]];
} else {
out[j - 1].push(prev);
}
}
//out -> [["a","a"],["b","b","b"],["c","c","c"]]
Demo
Note: the || !out.length check is just handle arrays that start with undefined correctly, but feel free to remove it if this will never be the case

JavaScript lookup value from array, replace with next index

I have a string variable which is generated like this
domNodes += ''+this.tagName + "" + " ยป ";
I also have an array which houses a 2D array with a string to lookup and a string to replace it with:
var replaceTags = [["i", "em"], ["b", "strong"]];
If this.tagName == i then replace with em the same for b and strong.
I know this is simple because I've done it before, I just can't remember how :(
http://jsfiddle.net/Nw45Y/
var replaceTags = [["i", "em"], ["b", "strong"]];
var tn = this.tagName;
for (var i =0; i < replaceTags.length; i++) {
tn = tn.replace(new RegExp(replaceTags[i][0], 'g'),replaceTags[i][1]);
}
You can create a function like this:
function replaced(x) {
var replaceTags = [["i", "em"], ["b", "strong"]];
for(var i = 0; i < replaceTags.length; i++) {
if(replaceTags[i][0] === x) return replaceTags[i][1];
}
return x;
}
Then call it like:
data-node="'+replaced(this.tagName.toLowerCase())+'"

Categories