I have an array that contains multiple strings. I need to store each string minus the first letter and then concatenate them into a sentence.
I am trying:
var missingFirstLetter = array[i].splice(1);
What I have found online guides me to believe this should work, but it doesn't work as intended.
You should slice (not splice!) each element of the array and then store it back into an array, which you can do with Array#map, which maps each element to a new value, in this case the string without the first letter:
var arrayNoFirstLetter = array.map(el => el.slice(1));
This will iterate through the array and map each element to a new string without the first letter and store the new array of strings into arrayNoFirstLetter. Make sure to use String#slice to get a section of a string, because there is not String#splice method. (maybe you mistook it for Array#splice?) Then you can use Array#join to join them with a delimiter (which is the string between each element when joined together):
var joined = arrayNoFirstLetter.join(""); //join with empty space for example
For example:
var array = ["Apples", "Oranges", "Pears"];
var arrayNoFirstLetter = array.map(el => el.slice(1)); // ["pples", "ranges", "ears"]
var joined = arrayNoFirstLetter.join(""); // "pplesrangesears"
Try this:
var a=["hHello","+-I-am","d-evil"];
var x;
var z="";
for(var i=0;i<a.length;i++){
x=a[i].substring(1);
z=z+x;
}
console.log(z);
Result is :
Hello-I-am-evil
Is it what you wanted?
var strings = ['string1', 'string2', 'string3'],
stringsNoFirstCh = [];
for(key in strings){ // Iterates through each string in an array
let string = strings[key];
var s = string.substring(1); // Gets a string starting from index 1, so omits the first char
stringsNoFirstCh.push(s); // Add to a new array: ['tring1', 'tring2', 'tring3']
}
var string = stringsNoFirstCh.join(''); // Transform to a string: tring1tring2tring3
I have an array with items and I want to group them according the first letter but when I push the item to the array it shows empty "Array[0]" while there are clearly items in it.
Apparently I'm doing something wrong but i have no idea what.
var group = [];
var alphabetArray = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
alphabetArray.forEach(function(letter) {
group[letter] = group[letter] || [];
group[letter].push({
key: letter,
letter
});
});
console.log(group);
Arrays are designed to hold an ordered set of data represented by property names which are integers.
You are assigning property names which are letters.
Arrays are not designed to hold that kind of data and console.log doesn't display those properties for arrays.
Don't use an array. Use an object. Objects are designed to hold unordered data with arbitrary property names. If order matters, then you might want to use a Map instead.
You are looking to create an object instead of an array. Change the [] to {}
An Array expects an int as index, the object can take a string
var group = {}; // Object instead of Array
var alphabetArray = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
alphabetArray.forEach(function(letter) {
group[letter] = group[letter] || [];
group[letter].push({
key: letter,
letter
});
});
console.log(group);
I guess you want to transform each letter to structure. I f so, you need Array.map:
var alphabetArray = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
var group = alphabetArray.map(function(letter) {
return {
[letter]: letter
};
});
console.log(group);
I have an array of character with commas separating them. I need to split an array but retain my comma inbetween each character.
See below for an example array:
var myArray = [a,,,b,c,d,,,]
There's a comma in there between the characters "a" and "b". I need to retain the comma when converting the array to a string.
The output string needs to resemble this:
a,bcd,
This is what i'm currently doing to retain the commas:
myArray.toString().replace(/,/g, "");
The Array's toString() method basically does a join(",") which is why you are getting the extra commas in your string.
Instead use join("") if you want to join the elements without the delimiter being added as part of the string
var myArray = ["a",",","b","c","d",",",]
document.body.innerText = myArray.join("");
How about you use :
var myArray = [a,,,b,c,d,,,];
var str = myArray.join();
This will give a string of array elements, preserving the commas.
if you want it to maintain the centre comma you should create your array as
var myArray = [a,",",b,c,d,",",];
this will then treat the middle comma in the set of 3 as a string containing that character rather than the array seperator
You could change your regex, to replace item,item for item item.
myArray.toString().replace(/([a-z,]),([a-z,])/g, "$1$2")
Basically you have a sparse array and want to extract only filled values and convert it to string ? Here is one, probably not the best, solution :
var myArray = ['a',',',',','b',',','c']
var resultArray = [];
for(var i = 0; i < myArray.length; i++){
if(myArray[i] !== ','){// allow 0, false, null values, but not undefined
resultArray.push(myArray[i]);
}
}
console.log(resultArray);
Working plnkr : http://plnkr.co/edit/55T6PGI9DuTlvy6k88hr?p=preview, check the console of your broswer.
If this is an actual array of strings and you wanted only those with actual values, you could use the filter() function to filter out any non-undefined ones :
// Your example array
var input = ['a',,,'b','c','d',,,];
// Remove any undefined elements
var output = input.filter(function(e){ return e; }); // yields ['a','b','c','d']
You could then use the join() function to create a string with your elements :
var result = output.join(); // yields "a,b,c,d"
Example Snippet
var input = ['a',,,'b','c','d',,,];
document.write('INPUT: ' + input + '<br />');
var output = input.filter(function(e){ return e; });
document.write('OUTPUT: ' + output);
I'm trying to create an array from a string that is separated into different words, each of which would be a separate element. The split() works fine here, however, the string is stored as a list in the array. How do I store a string into an array such that each word will be its own element in the array and not a list?
var myArray = [];
var string = "Hello, my name is Cameron and I like turtles."
myArray.push(input.split(" "));
console.log(myArray.indexOf('name')); //-1
console.log((myArray[0])); //prints string in list
console.log((myArray[1])); //undefined
console.log((myArray[2])); //undefined
this should work :
var string = "Hello, my name is Cameron and I like turtles."
var myArray = string.split(" ");
You are pushing an array into another array. You can initialize the value with the splitted string directly.
var string = "Hello, my name is Cameron and I like turtles.",
myArray = string.split(" ");
<script>
var string = "Hello, my name is Cameron and I like turtles.";
var toArray = string.split("");
console.log(toArray();//Will Display string as array
</script>
Here you go
So you've created an array and string, that's fine.
var myArray = [];
var string = "Hello, my name is Cameron and I like turtles."
Now you're splitting the string and pushing the result of that to your first array.
myArray.push(input.split(" "));
This is where I think you're going wrong. You need to add the results to your original array, however you are adding them all as one item and in turn creating a multidimensional array.
You can either override your array:
myArray = input.split(" ")
Or concat them. This might be a better approach if you need to do it multiple times.
myArray.concat(input.split(" "));
I want to extract all JSON objects from a string randomly containing them and add them to an array.
Sample string:
"I was with {"name":"John"}{"name":"Anne"}{"name":"Daniel"} yesterday"`
how can i extract the JSON objects from this sample string?
One approach to this is to use the str.search(regexp) function to find all parts of it that fulfill the JSON regex found here. So you could write a function that searches over the string for regexp matches.
To actually extract the object from the string you could use these two functions for the regex and then loop over the string until all objects have been found.
var match = str.match(regex);
var firstIndex = str.indexOf(match[0]);
var lastIndex = str.lastIndexOf(match[match.length-1]);
var JSONobjects = [];
while( str.match(regex){
//extract the wanted part.
jsonObject = substr(str.indexOf(match[0],str.lastIndexOf(match[match.length1-]));
//remove the already found json part from the string and continue
str.splice(str.indexOf(match[0],str.indexOf(match[0] + jsonObject.length());
//parse the JSON object and add it to an array.
JSONobjects.push(JSON.parse(jsonObject));
}
var a = JSON.parse('{"name":"John"}');
a ==> Object {name: "John"}
var b = [];
b.push(a);