How to extract value from an Array in Javascript - javascript

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

Related

How to convert an array of json objects to string and then convert it back to array of json objects in Node.JS

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)

How to create a string query in javascript?

i was given a homework problem to be able to create a query string based on certain parameters in an array? I am still fairly new to javascript so have some success with it but would appreciate if someone can check my code please. Thank you to everyone in advance.
I am using forEach to loop through the array to get the values and using string concatenation to get some url. I have made a sample codepen for it.
https://codepen.io/anon/pen/pmRXzg
let Person = {
name: ['Sam', 'Daisy'],
food: ['banana', 'Apple']
}
let handler = Object.entries(Person)
handler.forEach(function(element) {
console.log(element)
})
let myUrl = Object.entries(handler).map(key => key + '=' +
handler[key]).join('&')
let visitUrl = "http://someURLString/?" + myUrl
console.log(myUrl)
console.log(visitUrl)
How can i get my final result to look like
someUrlString/?name=Sam,Daisy&food=banana,apple
You can use map() on Object.entries() and then join() entries by = and then join result by &
let Person = {
name: ['Sam','Daisy'],
food: ['banana','Apple']
}
let res = Object.entries(Person).map(x=> x.join('=')).join('&');
console.log(res)
Explanation:
Object.entiries() return an array of arrays. Each array contain key value pair. In this case entries will be [['name', ['Sam','Daisy']], ['food', ['banana','Apple']]].
Now we use map() on array. map() is takes a callback. It that callback first argument(in above case its x) is current element of array through which we are iterating. map() creates new array of same length based on the value returned from callback. In above case value returned is x.join('=')
join() is method which converts array to string by adding a given substring b/w each of them. So when apply join() on
[food , ['banana','Apple']].join('=')
it will become
"food=banana,Apple"
The array ['banana','Apple'] is converted to a string implicitly. So ['banana','Apple'] is banana,Apple
In the last part we get array ["name=Sam,Daisy","food=banana,Apple"] and we join() it by &.
The point is that when we array is converted to string. It returns string in which all elements are separated by ,
You can take advantage of .entries, .map and .join to:
Map [key,value] pairs of Person.
Transform their value to a single string, by eventually manipulating data.
Join them to return the final string.
let Person = {
name: ['Sam', 'Daisy'],
food: ['banana', 'Apple']
}
const res = Object.entries(Person).map(([entryName, entryValues]) => {
return `${entryName}=${entryValues.map(i => i.toLowerCase()).join(',')}`;
}).join('&');
const url = `someUrlString/?${res}`;
console.log(url);

How to dynamically set the key in a reduce function

I have a .txt file with all the scrabble letter quantities in:
A-9, B-2, C-2, D-4, E-12, F-2, G-3, H-2, I-9, J-1, K-1, L-4, M-2, N-6, O-8, P-2, Q-1, R-6, S-4, T-6, U-4, V-2, W-2, X-1, Y-2, Z-1
I am trying to get an array of objects from this, where the key is the letter, and the value is the number.
The problem I am having is where I am trying to set the key to be the first item in the array (that I split earlier) [A, 9].
The code I have is as follows. Any tips would be gratefully received :)
import fs from 'fs'
var output = fs.readFileSync('scrabble-quantities.txt', 'utf-8')
.trim()
.split(', ')
.map(item => item.split('-'))
.reduce((quantities, item) => {
quantities.push({
item[0]: item[1]
})
return quantities
}, [])
Thanks
I would use an object instead of an array. It's easier and more natural how JS works:
// ...
.reduce((quantities, item) => {
quantities[item[0]] = item[1];
return quantities;
}, {});
The resulting output object is then (in JSON notation):
{
"A": 9,
"B": 2,
// ...
"Z": 1
}
EDIT: mind the value type
If you want the value to be an actual number you will have to parse it in the assignment with:
parseInt(item[1], 10)
To create a key (property name) dynamically, you need to do one of two things:
In ES5 and earlier, you have to create the object and then set the property:
var o = {};
o[item[0]] = item[1];
In ES2015 (aka ES6) and later, you can use a dynamic property name in a property initializer via []:
// ES2015 (ES6) ONLY
quantities.push({
[item[0]]: item[1]
})
That said, I'd come at the problem differently, using regex and ending up with an object keyed by the letter rather than an array of objects:
var str = "A-9, B-2, C-2, D-4, E-12, F-2, G-3, H-2, I-9, J-1, K-1, L-4, M-2, N-6, O-8, P-2, Q-1, R-6, S-4, T-6, U-4, V-2, W-2, X-1, Y-2, Z-1";
var quantities = {};
str.match(/[A-Z]-\d/g).forEach(function(entry) {
quantities[entry.charAt(0)] = +entry.replace(/.-/, '');
});
console.log(quantities);
Then, looking up the quantity of a letter becomes quantities.A (or quantities[letter] if letter is a variable containing "A"):
console.log(quantities.A); // 9

Substring of a file

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);

Arrays and strings in javascripts

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]);

Categories