I have a file that is structure like this :
var file = "a|b|c|d, a|b|c|d, a|b|c|d, a|b|c|d, a|b|c|d";
Now I would extract all letters "c" and "d" of this file and put those letter in array, structure like this:
var array = [
[a,b,1],
[a,b,2],
[a,b,3],
[a,b,4],
[a,b,5]
];
How can I do that? It is possible?
--------------EDIT----------------------
And if I have an array structured like this?
exArray = [
["a":"one", "b":"two", "c":"three", "d":"four"],
["a":"five", "b":"six", "c":"seven", "d":"eight"]
];
The new array must be:
var array = [
[two,three,1],
[six,seven,2]
];
To get your desired output, this will do the trick:
var file = "a|b|c|d, a|b|c|d, a|b|c|d, a|b|c|d, a|b|c|d";
var array = file.split(", ") // Break up the original string on `", "`
.map(function(element, index){
var temp = element.split('|');
return [temp[0], temp[1], index + 1];
});
console.log(array);
alert(JSON.stringify(array));
The split converts your file string to an array like this:
["a|b|c|d", "a|b|c|d", "a|b|c|d", "a|b|c|d", "a|b|c|d"];
Then, map is called on that array, passing each "a|b|c|d", along with it's position in the array to the callback, which splits the string, and returns an array containing the first 2 elements, and it's id (index + 1).
You can also do the callback in the map slightly differently:
.map(function(element, index){
return element.split('|').slice(0, 2).concat(index + 1);
});
This method uses the same split, then uses slice to get the first 2 elements from the array, and concats the id to the array with 2 elements returned from slice.
This way, you don't use a temporary variable, there:
element // "a|b|c|d"
.split('|') // ["a", "b", "c", "d"]
.slice(0, 2) // ["a", "b"]
.concat(index + 1) // ["a", "b", id]
Try to use split() function and map() function
var file = "a|b|c|d, a|b|c|d, a|b|c|d, a|b|c|d, a|b|c|d";
file.split(',').map(function(el, index) {
var arr = el.split('|');
return [arr[0], arr[1], index+1]
});
If I understood you correctly, this should work:
function transformFile(file) {
return file.split(',').map(function(el) {
return el.split('|'); }
);
}
split() function transforms a string to an array taking its parameter as an item separator. You can read more about it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
map() function takes an array and iterates over every item changing it in the way you define in the callback function. And here's the reference: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map
So we're taking a string and first we split it in four arrays - each containing a|b|c|d string. Then we take each of those string and split it again (this time using | as separator) to transform a|b|c|d string into [a, b, c, d] array. So after those operations we end up with an array of arrays.
Try to use split() and replace() function.
var file = "a|b|c|d,a|b|c|d,a|b|c|d,a|b|c|d, a|b|c|d";
var NewFile =[];
var i = 1;
file.split(',').forEach(function(el) {
NewFile.push( el.replace("c|d", i).split("|"));
i++;
});
console.log(NewFile);
Related
I have an array of json objects like this:
var b = [{"n":11,"np":11,"g":2,"v":10},{"n":6,"np":6,"g":4,"v":5},{"n":8,"np":8,"g":4,"v":10},{"n":9,"np":9,"g":4,"v":10}]
Then I convert each object of the array to a string:
b = b.map(function(card){
return JSON.stringify(card);
});
Then I convert the array to string as well using the join function:
b = b.join("|");
This is the output of b:
{"n":11,"np":11,"g":2,"v":10}|{"n":6,"np":6,"g":4,"v":5}|{"n":8,"np":8,"g":4,"v":10}|{"n":9,"np":9,"g":4,"v":10}
Now I need to convert everything back so I use split:
b = b.split("|");
Output:
[ '{"n":11,"np":11,"g":2,"v":10}',
'{"n":6,"np":6,"g":4,"v":5}',
'{"n":8,"np":8,"g":4,"v":10}',
'{"n":9,"np":9,"g":4,"v":10} ]
Now I try to go through each element and convert back to json object with JSON.parse:
var newArr = b.forEach(function(card){
var newCard = JSON.parse(card);
return newCard;
});
However, after that it gives me "undefined" as an output and if I try to use pop() to remove one element from the new array it gives me an error:
var singleCard = newArr.pop();
Error:
----- process errTypeError: Cannot read property 'pop' of undefined
The problem is in the last step when getting newArr, Array#forEach doesn't return an array, use Array#map instead:
var b = [{"n":11,"np":11,"g":2,"v":10},{"n":6,"np":6,"g":4,"v":5},{"n":8,"np":8,"g":4,"v":10},{"n":9,"np":9,"g":4,"v":10}]
b = b.map(function(card){ return JSON.stringify(card); });
b = b.join("|");
b = b.split("|");
var newArr = b.map(function(card){
var newCard = JSON.parse(card);
return newCard;
});
console.log(newArr);
I found out the problem:
It turned out that my last output was not a simple array, but a JSON array
[ '{"n":11,"np":11,"g":2,"v":10}',
'{"n":6,"np":6,"g":4,"v":5}',
'{"n":8,"np":8,"g":4,"v":10}',
'{"n":9,"np":9,"g":4,"v":10} ]
So all I had to do was this after using the split:
b = b.map(JSON.parse)
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 am querying my db in node and have got the result in the form of an object like this - [ [1234] ].
I want to extract this value and convert it into a string and then pass it onto the client side. I have written the other required code but I am not able to get value from this object. Can anyone help me in getting the value and converting it to string?
Since, the result you've got is a two-dimensional array, you can get the value and convert it into a string (using toString() method) in the following way ...
var result = [ [1234] ];
var string;
result.forEach(function(e) {
string = e.toString();
});
console.log(string);
** this solution will also work if you have multiple results, ie. [ [1234], [5678] ]
You have a nested array, meaning that you have an array inside another array:
[ [1234] ]
// ^-^====^-^
To get the first value of the parent array, use the square brackets: [0]. Remember that indexes start at 0!
If you have val = [[1234]], val[0] gets the enclosed array: [1234]. Then, 1234 is a value in that array (the first value), so you use the square brackets again to get it: val[0][0].
To convert to string, you can use + "" which forces the number to become a string, or the toString() method.
var val = [[1234]];
var str = val[0][0] + "";
// or val[0][0].toString();
console.log(str, typeof str);
You can read more about arrays here.
var response = [ [1234] ];
console.log(response[0][0]);
to extract values from a string array or an array we can use .toString()
Ex:
let names = ["peter","joe","harry"];
let fname = names.toString();
output = peter ,joe,harry
or
let name:string[] = this.customerContacts.map(
res => res.firstname
let fname =name.toString();
Using De-structuring Array concept:
const arr = [[1, 2, 3, 4, 5]];
const [[p, q, r, s, t]] = arr;
console.log(p, q, r, s, t);
Output: 1 2 3 4 5
I will start this question with the statement that I'm really bad with regex.
Said this, I wonder if possible to filter an array using jquery $.grep, match strings with an specific string, something like this:
var a = ["ABC:12", "xx:ABC:2", "ASD:3", "xx:ASD:5"];
var s = a.split(",");
var array = $.grep(s, function(x, y) {
return ??????;
});
so after applying $.grep or any other function which could help, i will need the after ":" number of those with ABC, so my new array would be:
array[12, 2];
Any help with this??? I would really appreciate!
$.grep only select elements of an array which satisfy a filter function.
You need additional step to $.map all numbers from grepped array.
var a = ["ABC:12", "xx:ABC:2", "ASD:3", "xx:ASD:5"];
var b = $.grep(a, function(item) {
return item.indexOf("ABC:") >= 0;
});
var array = $.map(b, function(item) {
return item.split(":").pop();
});
Try
var a = ["ABC:12", "xx:ABC:2", "ASD:3", "xx:ASD:5"];
// map array ,
// test array items for "ABC" string ,
// filter `Number` in strings containing "ABC" ,
// return filtered Numbers , in newly mapped array
var s = $.map(a, function(n) {
return (/ABC/.test(n) ? Number(n.split(":").filter(Number)) : null)
}); // [12, 2]
Array1 = ['1,2,3']
How can I retrieve the numerical values by transforming it into non-string?
I've been trying parseInt, but I can only manage to get 1 as end-result.
Thanks.
If you start with an array containing a string, like in your example, you need to use split().
Example:
Array1 = ['1,2,3'];
var new_array = Array1[0].split(','); // new_array is ["1", "2", "3"]
for (var i = 0; i < new_array.length; i++) {
new_array[i] = parseInt(new_array[i]);
}
// new_array is now [1, 2, 3]
I would re-look why you're storing a comma separated string as an array element; but, if the reasoning is valid for your particular design, the question is do you have an array with more than one comma-separated string like this?
If you can, re-work your design to actually use an array of integers, so use:
var arr = [1,2,3];
instead of ['1,2,3'].
If you are storing comma separated strings as array elements, you can get each index as an array of integers using something like the following:
var array1 = ['1,2,3', '4,5,6,7'];
function as_int_array(list, index) {
return list[index].split(',').map(function(o) { return parseInt(o,10); });
}
console.log("2nd element: %o", as_int_array(array1, 1));
// => 2nd element: [4,5,6,7]
Hope that helps.
Generally parseInt() takes anything(most of the time string) as input and returns integer out of that input. If it doesn't get any integer then it returns NaN.
Why you are getting 1 !!!
Whenever you are using parseInt() it tries to read your input character by character. So according to your input
var Array1 = ['1,2,3'];
first it get's '1' and after that ',' (a comma, which is not a number) so it converts '1' into Integer and returns it as your result.
Solution of your problem :
var Array1 = ['1,2,3'];
//just displayed the first element of the array, use for or foreach to loop through all the elements of the array
alert(Array1[0].split(',')[0]);