Append to each element in an array in Javascript - javascript

With an array, how would I append a character to each element in the array? I want to add the string ":" after each element and then print the result.
var a = [54375, 54376, 54377, 54378, 54379, 54380, 54381, 54382, 54383, 54384, 54385, 54386, 54387, 54388, 54389, 54390, 54391, 54392, 54393, 54394, 54395, 54396, 54397, 54400, 54402, 54403, 54405, 54407, 54408];
For example: 54375:54376:54377

a = a.map(function(el) { return el + ':'; });
Or if you want to join them into a string:
var joined = a.join(':');

If you are looking for a way to concatenate all the elements with :, you can use this
var result = "";
for (var i = 0; i < a.length; i += 1) {
result += a[i] + ":";
}
result = result.substr(0, result.length-1);
Or even simpler, you can do
a = a.join(":");
If you are looking for a way to append : to every element, you can use Array.prototype.map, like this
a = a.map(function (currentItem) {
return currentItem + ":";
});
console.log(a);
If your environment doesn't support map yet, then you can do this
for (var i = 0; i < a.length; i += 1) {
a[i] = a[i] + ":";
}

Related

Duplicate a character depending on its position in a string

I would like to duplicate every single letter in my string and uppercasing the first letter.
Like this case:
accum("abcd") -> "A-Bb-Ccc-Dddd".
However, it alters the first letter of the string. I think I should add another iterator called "j". But I don't know how to do it.
Precisely, the only task remaining in my code is to move on to the next letter while saving the changes made for the first letter.
function accum(s) {
var i = 0;
while ( i<s.length){
for (var j =i; j<i ; j++) {
s=s[j].toUpperCase()+s[j].repeat(j)+"-";
i+=1;
}
}
return s.slice(0,s.length-1);
}
Try this:
function accum(s) {
let newString = '';
for(let i = 0; i < s.length; i++) {
newString += s[i].toUpperCase() + s[i].repeat(i) + "-";
}
return newString.slice(0, newString.length - 1);
}
I guess you don't need two repetition loops at all (either you can keep the for or the while, i kept the for).
Your fundamental mistake was in this line: s=s[j].toUpperCase()+s[j].repeat(j)+"-"; where you replaced s with the new string instead of concatenating it (s += instead of s = ). Which would be wrong anyway because you are replacing the original string. You need another empty string to keep the changes separated from the original one.
Do this:
function accum(s) {
accumStr = '';
for (var i=0; i < s.length; i++) {
for (var j = 0; j <= i; j++) {
accumStr += j !== 0 ? s[i] : s[i].toUpperCase();
}
}
return accumStr;
}
console.log(accum('abcd')) //ABbCccDddd
Try this:
function accum(s) {
let strArr = s.split('');
let res = [];
for (let i in strArr) {
res.push(strArr[i].repeat(parseInt(i)+1));
res[i] = res[i].charAt(0).toUpperCase() + res[i].slice(1);
}
return res.join('-');
}
console.log(accum('abcd'))
try to use reduce method
const accum = (str) => {
return [...str].reduce(
(acc, item, index, arr) =>
acc +
item.toUpperCase() +
item.repeat(index) +
(index < arr.length - 1 ? "-" : ""),
""
);
};
console.log(accum("abcd")); //A-Bb-Ccc-Dddd

How to change multiple values in the array JavaScript

I have an array created with a for loop that has 50 values.
var array = [];
array [0] = {
selection : 0
}
var number = 1;
for (i = 0; i < 50; i++){
array[i].selection = number;
number ++;}
How to change the value for the array[i-20].selection? I don't want to use array[30].selection
It usually works if use array[i-1].selection or array[i+1].selection but doesn't work if use anything greater than one.
Thanks
You wanted Array of Objects and not Array with single Object, right ?
var array = [];
var number = 1;
fillFrom(3, 1); // should push instead of setting and start from zero but ;-)
var res = '<table width=1><tr><td>' + JSON.stringify(array).replace(/,/g, ',<br>') + '</td>';
fillFrom(0, -49);
res += '<td>' + JSON.stringify(array).replace(/,/g, ',<br>') + '</td></tr></table>';
document.body.innerHTML = res;
function fillFrom(start, number) {
for (i = start; i < 50; i++) {
if (array[i] === undefined) array[i] = {
selection: number
};
else array[i].selection = number;
number++;
}
}

Doubling each letter in a String in js

I need string Double each letter in a string
abc -> aabbcc
i try this
var s = "abc";
for(var i = 0; i < s.length ; i++){
console.log(s+s);
}
o/p
> abcabc
> abcabc
> abcabc
but i need
aabbcc
help me
Use String#split , Array#map and Array#join methods.
var s = "abc";
console.log(
// split the string into individual char array
s.split('').map(function(v) {
// iterate and update
return v + v;
// join the updated array
}).join('')
)
UPDATE : You can even use String#replace method for that.
var s = "abc";
console.log(
// replace each charcter with repetition of it
// inside substituting string you can use $& for getting matched char
s.replace(/./g, '$&$&')
)
You need to reference the specific character at the index within the string with s[i] rather than just s itself.
var s = "abc";
var out = "";
for(var i = 0; i < s.length ; i++){
out = out + (s[i] + s[i]);
}
console.log(out);
I have created a function which takes string as an input and iterate the string and returns the final string with each character doubled.
var s = "abcdef";
function makeDoubles(s){
var s1 = "";
for(var i=0; i<s.length; i++){
s1 += s[i]+s[i];
}
return s1;
}
alert(makeDoubles(s));
if you want to make it with a loop, then you have to print s[i]+s[i];
not, s + s.
var s = "abc";
let newS = "";
for (var i = 0; i < s.length; i++) {
newS += s[i] + s[i];
}
console.log(newS);
that works for me, maybe a little bit hardcoded, but I am new too))
good luck
console.log(s+s);, here s holds entire string. You will have to fetch individual character and append it.
var s = "abc";
var r = ""
for (var i = 0; i < s.length; i++) {
var c = s.charAt(i);
r+= c+c
}
console.log(r)
var doubleStr = function(str) {
str = str.split('');
var i = 0;
while (i < str.length) {
str.splice(i, 0, str[i]);
i += 2;
}
return str.join('');
};
You can simply use one of these two methods:
const doubleChar = (str) => str.split("").map(c => c + c).join("");
OR
function doubleChar(str) {
var word = '';
for (var i = 0; i < str.length; i++){
word = word + str[i] + str[i];
};
return word;
};
function doubleChar(str) {
let sum = [];
for (let i = 0; i < str.length; i++){
let result = (str[i]+str[i]);
sum = sum + result;
}
return sum;
}
console.log (doubleChar ("Hello"));

Javascript How to reverse space separated strings

The code below should reverse all the characters in a sentence, but it is unable to do so. This is child's play to me but at this moment it's not compiling. Can anyone figure out the issue?
Let's say:
"Smart geeks are fast coders".
The below code should reverse the above string as follows:
"trams skeeg era tsaf sredoc"
function solution(S){
var result = false;
if(S.length === 1){
result = S;
}
if(S.length > 1 && S.length < 100){
var wordsArray = S.split(" "),
wordsCount = wordsAray.length,
reverseWordsString = '';
for(var i = 0; i< wordsCount; i++){
if(i > 0){
reverseWordsString = reverseWordsString + ' ';
}
reverseWordsString = reverseWordsString + wordsAray[i].split("").reverse().join("");
}
result = reverseWordsString;
}
return result;
}
This should give you the result you're looking for.
function reverseWords(s) {
return s.replace(/[a-z]+/ig, function(w){return w.split('').reverse().join('')});
}
function reverseWords(s) {
var arr = s.split(" ");
s = '';
for(i = 0; i < arr.length; i++) {
s += arr[i].split('').reverse().join('').toLowerCase() + " ";
}
return s;
}
Wouldn't that do the job for you? Basically it just converts the string into an array, by splitting it on space. Then it loops over the array, adds every string reversed to a new string, and then it converts it to lowercase. For faster speed (nothing you would notice), you can just call newStr.toLowerCase() after the loop, so it will do it once instead of every time.

Javascript count unique array occurrence

Following were an output from an array returned by following function:
$scope.variantOptions = $scope.variantLists.join(", ");
medium,small,medium,small,small
How can I sort the result, so it represent the output as:
medium x 2,small x 3
EDIT
addCount function:
$scope.addCount = function($index){
$scope.counter = 1;
if($scope.activity['variant'][$index]['count'] != undefined ){
$scope.counter = parseInt($scope.activity['variant'][$index]["count"]) +1;
$scope.variantLists.push($scope.activity['variant'][$index]['variant_dtl_name']);
}
$scope.activity['variant'][$index]["count"] = $scope.counter;
console.log(arraySimplify($scope.variantLists));
};
Thanks!
pass your '$scope.variantLists' arry into this function it will give you the expected result.
function arraySimplify(arr){
arr.sort();
var rslt = [], element =arr[0] ,count = 0 ;
if(arr.length === 0) return; //exit for empty array
for(var i = 0; i < arr.length; i++){
//count the occurences
if(element !== arr[i]){
rslt.push(element + ' x ' + count);
count =1;
element = arr[i];
}
else{
count++;
}
}
rslt.push(element + ' x ' + count);
return rslt.join(', ');
}
Your code is working:
for (var i = 0;i < $scope.variantLists.length;i++) {
obj[arr[i]] = (obj[arr[i]] || 0) + 1;
}
Gives you an object:
obj = {medium: 2, small: 3}
To see it without having to go into the console, you can just alert the object after the 'for' loop:
alert(obj);
To get the EXACT string you want:
var string = "";
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var count = validation_messages[key];
string += key + " x " + count;
}
}
Although it may look like an entry in Code Golf but this is one of the rare times when Array.reduce makes sense.
var r = a.sort().reduce(
function(A,i){
A.set(i, (!A.get(i))?1:A.get(i)+1);
return A;
},new Map());
Which makes basically what Jon Stevens proposed but in a more modern and highly illegible way. I used a Map because the order in a normal Object dictionary is not guaranteed in a forEach loop. Here r.forEach(function(v,k,m){console.log(k + ":" + v);}) gets printed in the order of insertion.

Categories