How to take First letter from the string with comma separated? - javascript

I have one array and I store comma separated strings in the array. Now I want to take in the string every first letter take from the string with comma separated.
For ex => Abc, Xyz, Hji so now I want A, X, H.
Here below listed my code and array.
This is my code =>
var ArryString = [];
for (var i = 0; i < data.length; i++) {
ArryString.push(data[i].Str);
}
Current o/p =>
"Abc"
"Xyz,Hji,Lol",
"Uyi,Mno"
my expacted o/p= >
"A"
"X,H,L"
"U,M"

You could split the strings and take only the first character with a destructuring assignment and join the first characters for a string. Then map the new string for a new array.
var data = ["Abc", "Xyz,Hji,Lol", "Uyi,Mno"];
result = data.map(s => s
.split(',')
.map(([c]) => c)
.join());
console.log(result);

This is not looking good and amateurish but understandable.
var ArryString = [];
var data = ["Abc", "Xyz,Hji,Lol", "Uyi,Mno"];
var index=0;
for (var k in data){
var a=data[k].split(",");
ArryString[index]=a[0].charAt(0);
if(a.length > 1)
for (var l=1 ;l<a.length ; l++)
ArryString[index]+=","+a[l].charAt(0);
index++;
}
console.log(ArryString);

You can use charAt method Return the first character of a string.
var newString = [];
for (var i=0; i< newString.length; i++)
{
newString.push(ArrayString[i].charAt(0);
}

Here is a working example :
// We've got an array of comma separated worlds
// Sometimes we've got one, sometimes several
data=["Hello","i","have","one,array","and,i","store","comma,separated,string,in","the","array"];
// We want to ouput the same pattern but keeping the initial letter only
var result = [];
var items = [];
var aChar;
// We loop thru the data array
for (var i = 0; i < data.length; i++) {
// We make a small array with the content of each cell
items = data[i].split(",");
for (var j = 0; j < items.length; j++) { // We loop thru the items array
aChar = items[j].charAt(0); // We take the first letter only
if (aChar!="") // If the item/work was not empty the we keep only the initial letter in our items array
items[j] = aChar;
}
result.push(items.join(",")); // we store comma separated first letters in our result array
}
console.log(result)

Use the String.charAt() method for each string in the array and push the first character to a new array.
Example function:-
function takeFirstChar(arr){
var new_arr = [];
arr.forEach(function(el){
var firstLetter = el.charAt(0)
new_arr.push(firstLetter);
});
return new_arr;
}
takeFirstChar(['hello','cruel','world']);
//Output-> ['h','c','w']

Related

Reverse a list of characters

list = [c,a,r,p,e,t]
function reverse(list) {
var i =0; j= list.length-1;
while(i < j) {
var temp = list[i];
list[i] = list[j];
list[j] = temp;
i++;
j--;
}
return list;
}
Hello everyone, I am trying to solve the problem above. It works for an array of numbers. How can I adapt it to handle a list of characters?
Arrays can be reversed by design natively without the needs of a loop:
var list = ['c','a','r','p','e','t'];
var reversedList = list.slice(0).reverse();
Check the Mozilla Developer Network: Array.prototype.reverse() and Mozilla Developer Network: Array.prototype.slice() for more infomation.
just use .reverse(); and assuming c,a,r,p,e,t is a variable then use String() if you want to sort it by letter and use Number() if sort it by number.
sort by string:
var list = [String(c),String(a),String(r),String(p),String(e),String(t)].reverse();
sort by number:
var list = [Number(c),Number(a),Number(r),Number(p),Number(e),Number(t)].reverse();
Reference: .reverse() String() Number()
Your code throws - Uncaught ReferenceError: c is not defined. As you miss to place " or ' along with character.
Change your step array declaration step :
From : list = [c,a,r,p,e,t]
To : list = ['c','a','r','p','e','t'] or list = ["c","a","r","p","e","t"]
Your working code
var list = ['c','a','r','p','e','t'];
function reverse(list) {
var i =0; j= list.length-1;
while(i < j) {
var temp = list[i];
list[i] = list[j];
list[j] = temp;
i++;
j--;
}
return list;
}
//Call the method;
reverse(list);
jsfiddle working example :
https://jsfiddle.net/m6kt3eus/1/
Other simpler way to achieve this :
The simple way to reverse the array is reverse() in javascript
Following are the example code snippet:
var list = ['c','a','r','p','e','t'];
list.reverse();
console.log(list);
arr.reverse() is used for in place reversal of the array. The first element of the array becomes the last element and vice versa.
Syntax:
arr.reverse()
Argument
This function does not take any argument.
Return value
This function returns the reference of the reversed original array.
function reverse(list) {
var list2 = [];
for (let i = 0; i < list.length; i++)
list2.unshift(list[i]);
return list2;
}
var list = ['c', 'a', 'r', 'p', 'e', 't'];
console.log(reverse(list));

Ho to reverse split string into a JavaScript array?

I want to use one loop to split or explode a string into an array like
"Work" // -> var strArray = [k, rk, ork, work]
I tried for loop, but I know this is not an efficient.
for (let index = 0; index < word.length; index++)
{
strArray.push(word[word.length - 1]);
}
Any idea?
It looks like you may want to be sliceing your string. Here's something that'll do that:
function wordSplit(word) {
let strArray = [];
for (let i = 0; i < word.length; i++) {
strArray.push(word.slice(i));
}
return strArray;
}
And a fiddle: https://jsfiddle.net/13kephm9/7/
You can split the string, and iterate the array with Array#map, and generate the string using slice:
var word = 'work';
var result = word.split('').map(function(l, i) {
return word.slice(-i - 1);
});
console.log(result);
for (let index = 0; index < word.length; index++)
{
strArray.push(word.slice(index));
}
array string elements reversing
function rev(arr){
var text = new Array;
for(var i= arr.length-1;i>= 0;i--){
text.push(arr[i]);
}
return text.join();
}
console.log(rev(["a","b","c"]));
`print`

Add sums of array. Display one output

Update: The answer to this question is bellow. Thanks to dougtesting on a different thread. add array together, display sum
function hello() {
var arr = [];
for (var i = 0; i < 10; i++) {
arr.push(prompt('Enter number' + (i+1)));
}
var total = 0;
for(i=0; i<arr.length; i++) {
var number = parseInt(arr[i], 10);
total += number;
}
console.log(total);
}
//End of answer.
I am trying to have a user input 10 numbers. Then add those numbers together and display the output to the user. I was able to get the amount of inputs (10) into a array but I can't get arrays contents. I feel like I'm missing something simple. Would you mind taking a look?
// https://stackoverflow.com/questions/28252888/javascript-how-to-save-prompt-input-into-array
var arr = []; // define our array
for (var i = 0; i < 10; i++) { // loop 10 times
arr.push(prompt('Enter number' + (i+1))); // push the value into the array
}
alert('Full array: ' + arr.join(', ')); // alert the result
var arrEquals = []; //Empty Arr
arrEquals = arr.push(); //turn string into var
alert (arrEquals);//show string to admin for debug
//(for loop) console out # of array elements. does not output what is in array
//this is half the battle
for (var a = 0; a < arrEquals; a++){
var a = Number(a); //ensure input is Number()
console.log(a + "A"); //used for debug
}
//taks sums in array and adds them together
//this is the other half of the problem
// https://www.w3schools.com/jsref/jsref_forEach.asp
// var sum = 0;
// var numbers = [65, 44, 12, 4];
// function myFunction(item) {
// sum += item;
// demo.innerHTML = sum;
// }
This is probably one of the simplest examples of something that Javascript's built in array .reduce() function would be used for. Effectively, you're "reducing an array to a single value".
A reduce works by taking an array and running a function on each item. This "callback" function receives the value that the previous function returns, processes it in some way, then returns a new value. Worth noting, the reduce function also takes a 2nd argument that acts as the initial value that will be passed to the callback function the first time.
array.reduce(callbackFunction, initialValue);
Here's an example of reduce being used to sum an array.
var result = [1,2,3,4,5,6,7,8,9,10].reduce(function(accumulator, currentValue) {
return accumulator + currentValue;
}, 0); // start with an initial value of 0
console.log(result);
Using ES6 syntax, this can be further simplified to a one-liner
var result = [1,2,3,4,5,6,7,8,9,10].reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(result);
In your loop you're referencing arrEquals like for (var a = 0; a < arrEquals; a++){. you need to reference it like for (var a = 0; a < arrEquals.length; a++){ because just referencing the array doesn't tell javascript how long it is, or what number to count to. the .length returns a number, that number is how many items are in the array.
var arr = []; // define our array
for (var i = 0; i < 10; i++) { // loop 10 times
arr.push(prompt('Enter number' + (i+1))); // push the value into the array
}
arr = arr.join(', ');
alert('Full array: ' + arr); // alert the result
var arrEquals = []; //Empty array
arrEquals.push(arr); //assign arr string to an empty array
alert (arrEquals[0]); //show array[0] string to admin for debug
Is this what you are looking for? You need to put the arr.join() result to a variable, like itself.
You shouldnt be using arr.push() at all if you're not pushing new array items on it
//(for loop) console out # of array elements. does not output what is in array
//this is half the battle
for (var a = 0; a < arrEquals.length; a++){
//a is always a int in this case
console.log(a + "A"); //used for debug
}

Getting an array with lengths of words from a sentence -javascript

I'm trying to create a function that will tell me how long the longest word in a sentence is. My approach is to split the sentence into strings of words. I now have an array of strings. My problem is that I want to use this array to get another array of numbers i.e. the length of each word. How do I do this? My code is as below but I keep getting null.
function findLongestWord(str) {
var split = str.split(" ");
for (j = 0; j < split.length; j++)
var wordCount = split[j].length;
var lengths = [];
for (var i = 0; i < wordCount.length; i++) {
lengths.push(i);
}
return Math.max(...lengths);
}
If you are going to loop through all the words you can already find the max (longest) word in your input array.
function findLongestWord(str) {
var split = str.split(" ");
var maxLength = 0;
var longestWord = ""; // If no word is found "".length will return 0
var len = split.length;
for (j = 0; j < len; j++)
{
if (split[j].length > maxLength)
{
longestWord = split[j];
maxLength = split[j].length;
}
}
return longestWord;
}
And the returned value .length to get the length (or return maxLength if you so desire).
Note depending on your application punctuation might interfere with your algorithm.
I've made some comments about the mistakes in your code
function findLongestWord(str) {
// better use .split(/\s+/) instead to remove trailing space in the middle of sentence
var split = str.split(" ");
// this for loop is redundant, you have to wrap the code that you want to loop with curly brackets.
for (j = 0; j < split.length; j++)
// the value of j would be the length of split array.
var wordCount = split[j].length;
var lengths = [];
// since wordCount.length is undefined, so loop never gets excuted and your lengths array would be empty.
for (var i = 0; i < wordCount.length; i++) {
lengths.push(i);
}
// doing Math.max on empty array will return -Infinity
return Math.max(...lengths);
}
findLongestWord('hello there mate')
Below are my solutions. There are also more ways of doing what you want to do.
function findLongestWord(str) {
// trim trailing white space.
var split = str.trim().split(/\s+/);
var lengths = [];
// loop through array of words
for (j = 0; j < split.length; j++) {
// check the length of current words
var wordCount = split[j].length;
lengths.push(wordCount);
}
return Math.max(...lengths);
}
const sentence = 'hello its a me mariooooooo';
console.log(findLongestWord(sentence))
// one liner - using reduce function
const findLongestWord2 = (str) => str.trim().split(/\s+/).reduce((a, b) => a.length > b.length ? a.length : b.length, -Infinity);
console.log(findLongestWord2(sentence))
// less efficient but shorter - using sort
const findLongestWord3 = (str) => str.trim().split(/\s+/).sort((a, b) => a.length - b.length).pop().length;
console.log(findLongestWord3(sentence))
Create a function that takes an array of words and transforms it into an array of each word's length.
function multi(arr) {
var newarr = [];
for (var i = 0; i < arr.length; i++) {
newarr.push( arr[i].length);
}
return newarr;
}
You need to use var to create j in the first for loop like you did for the second for loop with i.
This can be done using the .map() method. You map the array of strings into an array of word lengths, and then return the Math.max() of the array of lengths, like so:
function findLongestWord(str) {
// map words into array of each word's length, grab highest #
return Math.max(...str.split(" ").map(str => str.length));
}
console.log(findLongestWord("The quick brown fox jumped over the lazy dog"));

How to create an array like this in JavaScript?

I want to create an array like this:
s1 = [[[2011-12-02, 3],[2011-12-05,3],[5,13.1],[2011-12-07,2]]];
How to create it using a for loop? I have another array that contains the values as
2011-12-02,3,2011-12-05,3,2011-12-07,2
One of possible solutions:
var input = ['2011-12-02',3,'2011-12-05',3,'2011-12-07',2]
//or: var input = '2011-12-02,3,2011-12-05,3,2011-12-07,2'.split(",");
var output = [];
for(i = 0; i < input.length; i += 2) {
output.push([t[i], t[i + 1]])
}
If your values always come in pairs:
var str = '2011-12-02,3,2011-12-05,3,2011-12-07,2',//if you start with a string then you can split it into an array by the commas
arr = str.split(','),
len = arr.length,
out = [];
for (var i = 0; i < len; i+=2) {
out.push([[arr[i]], arr[(i + 1)]]);
}
The out variable is an array in the format you requested.
Here is a jsfiddle: http://jsfiddle.net/Hj6Eh/
var s1 = [];
for (x = 0, y = something.length; x < y; x++) {
var arr = [];
arr[0] = something[x].date;
arr[1] = something[x].otherVal;
s1.push(arr);
}
I've guessed here that the date and the other numerical value are properties of some other object, but that needn't be the case...
I think you want to create an array which holds a set of arrays.
var myArray = [];
for(var i=0; i<100;i++){
myArray.push([2011-12-02, 3]); // The values inside push should be dynamic as per your requirement
}

Categories