How to join an array of strings without using .join()? - javascript

We're trying to write a function that takes an array of strings and a separator, and joins all the strings separated by such separator.
We are not allowed to use the .join() method.
So far, I'm stuck trying to iterate though all the strings adding a separator between them each time.
I tried something like:
var aName = ['Frank','Vincent','Zappa'];
var join = (arr, separator = " ") => {
for(var i = 0; i < arr.length; i++) {
return arr[i] + separator + arr[i+1];
}
};
join(aName, ' ');
//output: "Frank Vincent"
//expected output: "Frank Vincent Zappa"
Thanks for your help.

You can reduce the array:
function join(arr, separator)
{
return arr.reduce((str, a)=> {return a+separator+str})
}

To fix your current code, try concatenating instead, and return only at the end:
var aName = ['Frank', 'Vincent', 'Zappa'];
var join = (arr, separator = " ") => {
let result = '';
for (var i = 0; i < arr.length; i++) {
if (result) {
result += separator;
}
result += arr[i];
}
return result;
};
console.log(join(aName, ' '));

A very simple method is to append the separator only for the second element onwards:
const arr = ["Frank", "Vincent", "Zappa"];
const join = (arr, sep = " ") => {
if (!arr || !arr.length) return "";
let ret = arr[0];
for (let i = 1; i < arr.length; i++) {
ret += sep + arr[i];
}
return ret;
};
console.log(join(arr));
console.log(join(arr, "-"));

You can use the String constructor
var name = ['Frank', 'Vincent', 'Zappa'];
console.log(String(name).replace(/,/g,' '))

You could check the length of the array first and return an empty string if length is zero.
Otherwise take the first element as start value for the result and iterate from the second element and add the separator and the value of the array.
Proceed until no more elements. Then return the result string.
var join = (array, separator = ' ') => {
if (!array.length) return '';
var result = array[0];
for (var i = 1; i < array.length; i++) {
result += separator + array[i];
}
return result;
},
array = ['Frank', 'Vincent', 'Zappa'];
console.log(join(array, ' '));

The problem with your code is that you use return in a for loop which means that function will stop it's execution and return a value you write in return.
To avoid that you should write something like this:
var name = ['Frank','Vincent','Zappa'];
var join = (arr, separator = " ") => {
var result = '';
for(var i = 0; i < arr.length; i++) {
// adding to result string arr[i] and separator
result += arr[i] + separator;
}
// deleting separator in the end of string
return result.slice(0, -1);
};
join(name, ' ');

To be precise it is not possible to create a string without join() since JavaScript will internally always call join() for arrays. But if you just want to create your own join() function you can iterate through the array, add a separator to your current item and do this until you reached the end where you only add your current item without a separator.
var name = ['Frank', 'Vincent', 'Zappa'];
function join(arr, separator = " ") {
var str = "";
if (arr.length === 0) return str;
for (var i = 0; i < arr.length; i++) {
str += i !== arr.length - 1 ?
arr[i] + separator :
arr[i];
}
return str;
};
console.log(join(name, ' '));

A solution using a curried function in es2015
const joinStrings = glue = ' ' => strings => {
let res = '';
strings.forEach(str => res += glue + str);
return res.replace(glue, '');
}
const joined = joinStrings(', ')(['a', 'b', 'c']);
console.log(joined);

var names = ['Frank','Vincent','Zappa'];
const join = (names, separator) => {
let str = '';
for(let i = 0; i < names.length; i++) {
str += (str ? separator : '') + names[i];
}
return str;
}
console.log(join(names, ' '));

function joinFunction(arr){
let string = ''
for( let char of arr ){
string += char + ' '
}
console.log(string)
}
joinFunction(['Frank','Vincent','Zappa'])

Related

JavaScript How to Create a Function that returns a string with number of times a characters shows up in a string

I am trying to figure out how to make a function that takes a string. Then it needs to return a string with each letter that appears in the function along with the number of times it appears in the string. For instance "eggs" should return e1g2s1.
function charRepString(word) {
var array = [];
var strCount = '';
var countArr = [];
// Need an Array with all the characters that appear in the String
for (var i = 0; i < word.length; i++) {
if (array.indexOf(word[i]) === false) {
array.push(word[i]);
}
}
// Need to iterate through the word and compare it with each char in the Array with characters and save the count of each char.
for (var j = 0; j < word.length; i++) {
for (var k = 0; k < array.length; k++){
var count = 0;
if (word[i] === array[k]){
count++;
}
countArr.push(count);
}
// Then I need to put the arrays into a string with each character before the number of times its repeated.
return strCount;
}
console.log(charRepString("taco")); //t1a1co1
console.log(charRepString("egg")); //e1g2
let str = prompt('type a string ') || 'taco'
function getcount(str) {
str = str.split('')
let obj = {}
for (i in str) {
let char = str[i]
let keys = Object.getOwnPropertyNames(obj)
if (keys.includes(char)) {
obj[char] += 1
} else {
obj[char] = 1
}
}
let result = ''
Object.getOwnPropertyNames(obj).forEach((prop) => {
result += prop + obj[prop]
})
return result
}
console.log(getcount(str))
If the order of the alphanumeric symbols matters
const str = "10zza";
const counted = [...[...str].reduce((m, s) => (
m.set(s, (m.get(s) || 0) + 1), m
), new Map())].flat().join("");
console.log(counted); // "1101z2a1"
Or also like (as suggested by Bravo):
const str = "10zza";
const counted = [...new Set([...str])].map((s) =>
`${s}${str.split(s).length-1}`
).join("");
console.log(counted); // "1101z2a1"
A more clear and verbose solution-
Let m be max number of symbols in charset
Time complexity- O(n log(m))
Space complexity- O(m)
function countFrequencies(str) {
const freqs = new Map()
for (const char of str) {
const prevFreq = freqs.get(char) || 0
freqs.set(char, prevFreq + 1)
}
return freqs
}
function getCountStr(str) {
const freqs = countFrequencies(str)
const isListed = new Set()
const resultArray = []
for (const char of str) {
if (isListed.has(char)) continue
resultArray.push(char)
resultArray.push(freqs.get(char))
isListed.add(char)
}
return resultArray.join("")
}
console.log(getCountStr("egg"))
console.log(getCountStr("taco"))
console.log(getCountStr("10za"))
Using Set constructor, first we will get the unique data.
function myfun(str){
let createSet = new Set(str);
let newArr = [...createSet].map(function(elem){
return `${elem}${str.split(elem).length-1}`
});
let newStr = newArr.join('');
console.log(newStr);
}
myfun('array');

Creating a wave of string in Javascript

I can't seem to figure it out how to make a wave from a string in Javascript.
Rules:
The input will always be lower case string.
Ignore whitespace.
Expected result:
wave("hello") => ["Hello", "hEllo", "heLlo", "helLo", "hellO"]
wave (" h e y ") => [" H e y ", " h E y ", " h e Y "]
wave ("") => []
This is as far as I got. Current code will give me an answer ["hello", "hello", "hello", "hello", "hello"]. I'm thinking using second for loop and somehow capitalize each new letter but I'am stumped. Also I would appreciate if answer would avoid using loop inside loop O(n^2). Because of BIG O Scalability.
const wave = (str) => {
if(typeof str === 'string' && str === str.toLowerCase()){
for (let index = 0; index < str.length; index++) {
array.push(str);
}
for (let index = 0; index < str.length; index++) {
console.log(array);
}
}else{
alert(`${str} is either not a string or not lowercase`);
}
}
wave("hello");
You could take an outer loop for visiting the characters and if a non space character is found, create a new string with an uppercase letter at this position.
function wave(string) {
var result = [],
i;
for (i = 0; i < string.length; i++) {
if (string[i] === ' ') continue;
result.push(Array.from(string, (c, j) => i === j ? c.toUpperCase() : c).join(''));
}
return result;
}
console.log(wave("hello")); // ["Hello", "hEllo", "heLlo", "helLo", "hellO"]
console.log(wave(" h e y ")); // [" H e y ", " h E y ", " h e Y "]
console.log(wave("")); // []
.as-console-wrapper { max-height: 100% !important; top: 0; }
This does it. However, if you have spaces in your string, it will output string without any "waved letter" (since also space is handled):
const wave = (str = '') => {
return str
.split('')
.map((letter, i, arr) => `${arr.slice(0, i)}${letter.toUpperCase()}${arr.slice(i + 1, arr.length)}`.replace(/,/g, ''));
}
console.log(wave('wave'));
console.log(wave('foo bar'));
console.log(wave());
You can take each char in string in for loop and make it uppercase and the append with prefix and post fix string
var array=[];
const wave = (str) => {
if(typeof str === 'string' && str === str.toLowerCase()){
for (let index = 0; index < str.length; index++) {
if (str[index] === ' ') continue;
waveChar=str.charAt(index).toUpperCase();
preStr=str.substring(0,index);
postStr=str.substring(index,str.length-1);
array.push(preStr+waveChar+postStr);
}
}else{
alert(`${str} is either not a string or not lowercase`);
}
}
wave("hello");
console.log(array);
I use modify of String prototype :
for implementation of replaceAt .
// Modify prototype
String.prototype.replaceAt=function(index, replacement) {
return this.substr(0, index) + replacement+ this.substr(index + replacement.length);
}
function WaveFunction(str) {
var base = str;
var R = [];
var n =str.length;
for (var i=0 ; i<n ;i++){
str = base;
var c=str.charAt(i);
var res = c.toUpperCase();
// console.log(res);
str = str.replaceAt(i, res);
R.push(str);
}
return R;
}
var REZ = WaveFunction("hello");
console.log(REZ);
I use tradicional js. This works on 99% off today browsers.
Where answer very pragmatic. I use array access for string ;
Magic is "String.fromCharCode(str.charCodeAt(x) ^ 32);"
Make it inverse always when we call this line.
// Also tested UTF-8 non english chars
var index = 0;
var mydata= "helloçφšteti";
function wave (str){
var FINAL = [];
var newString = "";
for (var j =0; j < str.length; j++) {
for (var x =0; x < str.length; x++) {
var rez = "";
if (x == index) {
rez = String.fromCharCode(str.charCodeAt(x) ^ 32);
} else {
rez = str[x];
}
newString += rez ;
}
FINAL.push(newString);
newString = "";
index++;
}
return FINAL;
}
var rezArray = wave(mydata);
console.log(rezArray);
// Just for teory
console.log(Array.from([1, 2, 3], x => console.log(x)));

How to check if white spaces stored in an array in javascript?

I have stored a string in an array and want to check for white spaces that also stored in array. So that I can capitalize the each following word.
var arr = [];
arr = str.split("");
for(var i = 0; i < arr.length; i++) {
if(arr[i] === ' ') {
arr[i + 1].toUpperCase();
}
}
You're just missing an assignment:
var arr = [],
str = 'abc def ghi jkl';
arr = str.split("");
for (var i = 0; i < arr.length; i++) {
if (arr[i] === ' ') {
arr[i + 1] = arr[i + 1].toUpperCase();
// ^ You need to save the uppercase letter.
}
}
// Also "uppecase" the first letter
arr[0] = arr[0].toUpperCase();
console.log(arr.join(''));
You can also shorten the code a bit:
var str = 'abc def ghi jkl',
result = str.split(' ') // Split on `[space]`
.map(function(word) { // Do something with every item in the array (every word)
return word.charAt(0).toUpperCase() + // Capitalize the first letter.
word.slice(1); // Add the rest of the word and return it.
})
.join(' '); //Make a string out of the array again.
console.log(result);
You need to set the value of arr[i+1]:
var arr = [];
arr = str.split("");
for(var i=0; i<arr.length; i++)
{
if(arr[i]===' ')
{
arr[i+1]=arr[i+1].toUpperCase();
}
}
You can do it like this
var arr=[];
str="hello hi hello";
arr=str.split("");
arr1=arr.map(function(a,b){if(a==" "){arr[b+1]=arr[b+1].toUpperCase();} return(a)});
arr1[0]=arr[0].toUpperCase();
console.log(arr1);
great piece of code #cerbrus now we can even lowercase other letters in the word except the first one by add :-
var arr = [];
arr = str.split(" ");
str= arr.map(function(word)
{
return word.charAt(0).toUpperCase()+word.slice(1).toLowerCase();
}).join(" ");
return str;
var a = ['', ' ', 'aa '];
a.forEach(function(el){
if(el.trim() == ''){
console.log(el + ' -> white space');
}else{
var index = a.indexOf(el);
a[index] = el.toUpperCase();
console.log(a[index] + ' -> without white space');
}
});
console.log(a);

How to separate the string into two categories in jstl?

i have a string as,
String value = "Bhavani<>12<<>>Pallavi<>13<<>>Charanya<>14";
Now i need split the names and those values.
I am unable to identify what to do.
I need to print the values as
Output
---
-----------------------------
' Name ' value '
'------------'--------------'
' Bhavani ' 12 '
' Pallavi ' 13 '
' Charanya ' 14 '
' ' '
----------------------------'
I think it can be done in jstl level..
But can anyone help me how to split that string.
you can use str.replace to create an object:
strvalue = "Bhavani<>12<<>>Pallavi<>13<<>>Charanya<>14"
obj={};
strvalue.replace(/(\w+)<>(\w+)/g,function(_,m1,m2){
obj[m1]=m2
})
console.log(obj)
This should do it:
var str = 'Bhavani<>12<<>>Pallavi<>13<<>>Charanya<>14';
str = str.split('<<>>')
for(var i = 0; i < str.length; i++) {
str[i] = str[i].split('<>');
}
alert(str.join("\n"));
first split with <<>>
than split wiht <>
so you will get array with Bhavani , 12 in two indexes.
its simple to show in any way on view.
Personally, I'd store the key-value pairs in an object:
var myObj = {};
var string = 'Bhavani<>12<<>>Pallavi<>13<<>>Charanya<>14';
var stringArray = string.split('<<>>');
for(i in stringArray){
var key = stringArray[i].split('<>')[0];
var value = stringArray[i].split('<>')[1];
myObj[key] = value;
}
console.log('My object looks like', myObj);
Here is my solution, you'll get an array of objects with a name and value inside each object:
let value = "Bhavani<>12<<>>Pallavi<>13<<>>Charanya<>14";
let splittedString = value.split("<<>>");
let names = [];
splittedString.forEach(function(value) {
let splittedProps = value.split("<>");
names.push({
name: splittedProps[0],
value: splittedProps[1]
});
});
console.log(names);
var str = "Bhavani<>12<<>>Pallavi<>13<<>>Charanya<>14";
var strArr = str.split("<<>>");
var result = {};
for(var i in strArr){
var p = strArr[i].split("<>");
result[p[0]] = p[1];
}
console.log(result);
First split with <<>>
then split string with <>
var string = 'Bhavani<>12<<>>Pallavi<>13<<>>Charanya<>14';
string = string.split('<<>>');
for(var i = 0; i < string.length; i++) {
string[i] = string[i].split('<>');
}`
var string = 'Bhavani<>12<<>>Pallavi<>13<<>>Charanya<>14';
string = string.split('<<>>');
for(var i = 0; i < string.length; i++) {
string[i] = string[i].split('<>');
}
alert(string.join("\n"));
`
var str = "Bhavani<>12<<>>Pallavi<>13<<>>Charanya<>14";
var txt = str.split("<<>>").join("|").split("<>").join("|").split("|")
var object=[];
for (var i=0; i<txt.length;i=i+2){
object.push({Name:txt[i],Value:txt[i+1]});
}
console.log(object);

Reverse words(not letters) for a string without using .reverse()

The problem I am working on asks for me to write a function reverseMessage() that takes a string message and reverses the order of the words in place.
The answer I first came up with works but apparently doesn't meet the requirements of this task:
function reverseMessage(string) {
return string.split(" ").reverse().join(" ");
}
For example:
var string = "reversed are string your in words the now"
var results = "now the words in your string are reversed"
New solution:
I would like to split this string into an array and then loop through that array and swap the 1st index with the last index, the 2nd index with second to last index, 3rd index with the 3rd to last index, etc... until I meet in the middle.
I am trying to make the two different functions below work:
function reverseMessage(string) {
var array = string.split(" ");
//loop through array and replace first index with last index, second
index with second to last index, third index with third to last index, etc
for (var i = 0; i < array.length/2; i++) {
for (var j = (array.length-1); j > array.length/2; j--) {
array[i] = array[j];
array[j] = array[i];
messageSplit.join(",");
}
};
function reverseMessage2(string) {
var array = string.split(" ");
var newArray = []
for (var i = 0; i < array.length/2; i++) {
newArray.unshift(array[i]++);
newArray.join(",");
return newArray;
}
};
Am I on the right track?
function reverseMessage(string) {
var array = string.split(" ");
var result="";
for (var i = array.length-1; i >=0; i--) {
result+=array[i]+" ";
}
console.log(result);
};
So in yours reverseMessage function You are trying to swap variable for that you are doing
array[i] = array[j];
array[j] = array[i];
Which is giving array[i]=array[j] so let say array[i]="This" and array[j]="That"so according to yours code array[i] will be "That" and array[j] will also be "That" so you can try something like this:
function reverseMessage(string) {
var array = string.split(" ");
//loop through array and replace first index with last index, second
//index with second to last index, third index with third to last index, etc
for (var i = 0,j=(array.length)-1; i < array.length/2; i++) {
temp=array[i]
array[i] = array[j];
array[j]=array[i]
array[j] = temp; j--;}
console.log(array.join(" "));
}; reverseMessage("find you will pain only go you recordings security the into if");
try this one
function reverseMessage( str ) {
var arrStr = [];
var temp ="";
for(var i = 0 ; i < str.length ; i++)
{
if(str[i] === " ")
{
arrStr.push(temp);
temp="";
}
else
{
temp += str[i];
}
}
if(temp.length >= 0)
{
arrStr.push(temp);
}
var result = "";
for(var x=arrStr.length-1 ; x >=0 ; x--)
{
result += " "+arrStr[x];
}
return result;
}
console.log(reverseMessage("I am here"));
Well, someone's gotta do it:
function rev(s){
var a = s.split(/ /),
l = a.length;
i = l/2 | 0;
while (i--) a.splice(i, 1, a.splice(l-1-i, 1, a[i])[0]);
return a.join(' ');
}
document.write(rev('0 1 2 3 4 5 6 7 8 9'));
Using Array.split(), Array.pop(), Array.push() and String.substr():
var flip = function(str) {
var res = "", sp = " ", arr = str.split(sp);
while (arr.length)
res += arr.pop() + sp;
return res.substr(0, res.length - 1); //remove last space
};
alert(flip("reversed are string your in words the now"));
Using String.lastIndexOf() and String.substr():
var flip = function(str) {
var res = "", i, sp = ' ';
while (str) {
i = str.lastIndexOf(sp);
res += str.substr(i + 1) + sp;
str = str.substr(0, i);
}
return res.substr(0, res.length - 1); //remove last space
};
alert(flip("reversed are string your in words the now"));
What you want to do is split the words message into individual strings reverse them and then add them together, that will reverse them in place. Try
function reverseMessage(message){
var reversedMessage = ''; //A string to hold the reversed message
var words = message.split(' ');
for(var i =0; i< words.length; i++){
reversedMessage += reverse(words[i]) + " ";// add the reversed word to the reversed message, with a space at the end so the words dont touch
}
return reversedMessage
}
//A helper function that reverses a string
function reverse(s) {
var o = '';
for (var i = s.length - 1; i >= 0; i--)
o += s[i];
return o;
}
sources: http://eddmann.com/posts/ten-ways-to-reverse-a-string-in-javascript/
with `pop()` ;)
function reverseMessage(string) {
var array = string.split(" ");
var result="";
while (array.length > 0) {
result += array.pop()+" ";
}
console.log(result);
};

Categories