Related
I have an array like below and need to filter out the numbers from it ex: [1,2]
var str = [
"https://xx.jpg",
"https://xx.jpg",
"1",
"https://guide.jpg",
"2",
"/static.jpg"
]
I have the below code :
var filtered = str.filter(function(item) {
return (typeof item === "number")
});
but it is not filtering as it is a string.
How to do it?
I think this is the most precise way to filter out numbers from an array.
str.filter(Number);
If the array contains a number in the form of string, then the resulting array will have the number in the form of string. In your case, the resulting array will be ["1", "2"].
If the original array contains 0 or "0", then they will not be present in the resulting array.
If resulting array should include only integer numbers,
str.filter(Number.isInteger)
This will exclude the number in the form of string like "1", "2", etc.
For both integer and float numbers,
str.filter(Number.isFinite)
Making a small change to your code to make it work, this might possibly work.
var str = ["https://xx.jpg", "https://xx.jpg", "1", "https://guide.jpg", "2", "/static.jpg"];
var filtered = str.filter(function (item) {
return !(parseInt(item) == item);
});
console.log(filtered);
Or if you want the numbers:
var str = ["https://xx.jpg", "https://xx.jpg", "1", "https://guide.jpg", "2", "/static.jpg"];
var filtered = str.filter(function (item) {
return (parseInt(item) == item);
});
console.log(filtered);
Use isNaN().
var str=["https://xx.jpg","https://xx.jpg","1","https://guide.jpg","2","/static.jpg"];
var filtered = str.filter(function(item) {
return (!isNaN(item));
});
console.log(filtered);
var str = ["https://xx.jpg","https://xx.jpg","1","https://guide.jpg","2", "/static.jpg" ]
str.filter(item=>!isNaN(parseInt(item)))
parseInt convert number to integer and other values converted to "NaN", isNaN function validate value is either "NaN" or not
https://www.w3schools.com/jsref/jsref_isnan.asp
https://www.w3schools.com/jsref/jsref_parseint.asp
You could use a regular expression which test a string, if it contains only digits.
var array = ["https://xx.jpg", "https://xx.jpg", "1", "https://guide.jpg", "2", "/static.jpg"];
array = array.filter(function (a) {
return !/^\d+$/.test(a);
});
console.log(array);
If you want to check if a string only contains numeric digits, you can use regular expressions.
var str = ["https://xx.jpg", "https://xx.jpg", "1", "https://guide.jpg", "2", "/static.jpg"];
var filtered = str.filter(function (item) {
return item.match(/^-?\d+$/);
});
console.log(filtered);
const intArray = [];
const strArray = [];
const rest_test_parameters = (...args) => {
args.filter((item) => {
if (parseInt(item)) {
return intArray.push(parseInt(item));
}
strArray.push(item);
});
};
const objects = {
a: "a",
b: "c"
};
rest_test_parameters(1, 2, "99","hello", objects);
console.log("intArray", intArray);
console.log("strArray",strArray);
You usage func helper in filter
function isNumber(n) { return !isNaN(parseFloat(n)) && isFinite(n);}
str = str.filter(function(item) {
return (item !== 0) && ((!item) || (isNaN(item)));
});
The right side of the operation calls filter and passes a function which returns true if an item is not 0 and it is either falsey or not a number; otherwise it returns false. For instance "" or null should be kept in the array as far as the specification goes. With this approach we get the desired array and we assign it to the str variable.
const filterNumbers = [123456789, 'limit', 'elite', 987654321, 'destruction', 'present'];
const result = filterNumbers.filter(number => parseInt(number) == number);
console.log(result);
Here's similar code that returns the number instead of the string. The => is just alternative syntax for function and return (see arrow function expressions), but will yield the same result.
Most of the above answers are good, but missing one thing; filtering out array of numbers(neither integer, nor string form of numbers).
I haved added the snippet to address those little issues.
var str = ["https://xx.jpg", "https://xx.jpg", "1", "https://guide.jpg", "2.4", "/static.jpg","4"];
var filteredNumbers = str.filter(item=> parseFloat(item) == item).map(item=>parseFloat(item));
console.log(filteredNumbers);
Here's a one liner:
arr.filter(n => (parseInt(n)===0 || +n)).map(Number)
This is assuming it is a flat array and not a nested one.
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
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]);
I have an object like this coming back as a JSON response from the server:
{
"0": "1",
"1": "2",
"2": "3",
"3": "4"
}
I want to convert it into a JavaScript array like this:
["1","2","3","4"]
Is there a best way to do this? Wherever I am reading, people are using complex logic using loops. So are there alternative methods to doing this?
It's actually very straight forward with jQuery's $.map
var arr = $.map(obj, function(el) { return el });
FIDDLE
and almost as easy without jQuery as well, converting the keys to an array and then mapping back the values with Array.map
var arr = Object.keys(obj).map(function(k) { return obj[k] });
FIDDLE
That's assuming it's already parsed as a javascript object, and isn't actually JSON, which is a string format, in that case a run through JSON.parse would be necessary as well.
In ES2015 there's Object.values to the rescue, which makes this a breeze
var arr = Object.values(obj);
var json = '{"0":"1","1":"2","2":"3","3":"4"}';
var parsed = JSON.parse(json);
var arr = [];
for (var x in parsed) {
arr.push(parsed[x]);
}
console.log(arr)
Hope this is what you're after!
You simply do it like
var data = {
"0": "1",
"1": "2",
"2": "3",
"3": "4"
};
var arr = [];
for (var prop in data) {
arr.push(data[prop]);
}
console.log(arr);
DEMO
There is nothing like a "JSON object" - JSON is a serialization notation.
If you want to transform your javascript object to a javascript array, either you write your own loop [which would not be that complex!], or you rely on underscore.js _.toArray() method:
var obj = {"0":"1","1":"2","2":"3","3":"4"};
var yourArray = _(obj).toArray();
Nothing hard here. Loop over your object elements and assign them to the array
var obj = {"0":"1","1":"2","2":"3","3":"4"};
var arr = [];
for (elem in obj) {
arr.push(obj[elem]);
}
http://jsfiddle.net/Qq2aM/
var JsonObj = {
"0": "1",
"1": "2",
"2": "3",
"3": "4"
};
var array = [];
for (var i in JsonObj) {
if (JsonObj.hasOwnProperty(i) && !isNaN(+i)) {
array[+i] = JsonObj[i];
}
}
console.log(array)
DEMO
Try this:
var newArr = [];
$.each(JSONObject.results.bindings, function(i, obj) {
newArr.push([obj.value]);
});
You can use Object.assign() with an empty array literal [] as the target:
const input = {
"0": "1",
"1": "2",
"2": "3",
"3": "4"
}
const output = Object.assign([], input)
console.log(output)
If you check the polyfill, Object.assign(target, ...sources) just copies all the enumerable own properties from the source objects to a target object. If the target is an array, it will add the numerical keys to the array literal and return that target array object.
var obj = {"0":"1","1":"2","2":"3","3":"4"};
var vals = Object.values(obj);
console.log(vals); //["1", "2", "3", "4"]
Another alternative to the question
var vals = Object.values(JSON.parse(obj)); //where json needs to be parsed
Using raw javascript, suppose you have:
var j = {0: "1", 1: "2", 2: "3", 3: "4"};
You could get the values with:
Object.keys(j).map(function(_) { return j[_]; })
Output:
["1", "2", "3", "4"]
Not sure what I am missing here but simply trying the below code does the work. Am I missing anything here?
https://jsfiddle.net/vatsalpande/w3ew5bhq/
$(document).ready(function(){
var json = {
"code" :"1",
"data" : {
"0" : {"id":"1","score":"44"},
"1" : {"id":"1","score":"44"}
}
};
createUpdatedJson();
function createUpdatedJson(){
var updatedJson = json;
updatedJson.data = [updatedJson.data];
$('#jsondata').html(JSON.stringify(updatedJson));
console.log(JSON.stringify(updatedJson));
}
})
Assuming your have a value like the following
var obj = {"0":"1","1":"2","2":"3","3":"4"};
Then you can turn this into a javascript array using the following
var arr = [];
json = JSON.stringify(eval('(' + obj + ')')); //convert to json string
arr = $.parseJSON(json); //convert to javascript array
This works for converting json into multi-diminsional javascript arrays as well.
None of the other methods on this page seemed to work completely for me when working with php json-encoded strings except the method I am mentioning herein.
Here is an example of how you could get an array of objects and then sort the array.
function osort(obj)
{ // map the object to an array [key, obj[key]]
return Object.keys(obj).map(function(key) { return [key, obj[key]] }).sort(
function (keya, keyb)
{ // sort(from largest to smallest)
return keyb[1] - keya[1];
}
);
}
This is best solution. I think so.
Object.keys(obj).map(function(k){return {key: k, value: obj[k]}})
The accepted solution expects the keys start from 0 and are continuous - it gets the values into the array, but looses the indexes on the way.
Use this if your "object with numerical keys" does not fulfill those stricter assumptions.
//let sourceObject = ...
let destinationArray = [];
Object.keys(sourceObject).forEach(k => destinationArray[k] = sourceObject[k]);
var data = [];
data = {{ jdata|safe }}; //parse through js
var i = 0 ;
for (i=0;i<data.length;i++){
data[i] = data[i].value;
}
You can convert json Object into Array & String using PHP.
$data='{"resultList":[{"id":"1839","displayName":"Analytics","subLine":""},{"id":"1015","displayName":"Automation","subLine":""},{"id":"1084","displayName":"Aviation","subLine":""},{"id":"554","displayName":"Apparel","subLine":""},{"id":"875","displayName":"Aerospace","subLine":""},{"id":"1990","displayName":"Account Reconciliation","subLine":""},{"id":"3657","displayName":"Android","subLine":""},{"id":"1262","displayName":"Apache","subLine":""},{"id":"1440","displayName":"Acting","subLine":""},{"id":"710","displayName":"Aircraft","subLine":""},{"id":"12187","displayName":"AAC","subLine":""}, {"id":"20365","displayName":"AAT","subLine":""}, {"id":"7849","displayName":"AAP","subLine":""}, {"id":"20511","displayName":"AACR2","subLine":""}, {"id":"28585","displayName":"AASHTO","subLine":""}, {"id":"45191","displayName":"AAMS","subLine":""}]}';
$b=json_decode($data);
$i=0;
while($b->{'resultList'}[$i])
{
print_r($b->{'resultList'}[$i]->{'displayName'});
echo "<br />";
$i++;
}
How, in Javascript, can I cast a string as an array in the same way that PHP (array) does.
//PHP
$array = (array)"string"
Basically I have a variable that can be an array or a string and, if a string, I want to make it an array using an inline command.
Hacky, but works:
[].concat(arrayOrString);
//Usage:
[].concat("a");
//["a"]
[].concat(["a"]);
//["a"]
JavaScript is a prototyping language and does not have a type casting system.
One solution would be to check if your variable is a string and convert it into an array. For example :
if (typeof someVariable === 'string') someVariable = [someVariable];
In PHP, if you do a check on a string, like (ex: $array = 'string';) :
$array = (array) $array; // ex: "string" becomes array("string")
The JavaScript equivalent will be
arr = typeof arr === 'string' ? [arr] : arr;
If your variable arr is not necessarily a string, you may use instanceof (edit: or Array.isArray) :
arr = arr instanceof Array ? arr : [arr];
arr = Array.isArray(arr) ? arr : [arr];
var str = "string";
var array = str.split('');
console.log(array); // ['s', 't', 'r', 'i','n','g']
You can in jQuery...
var arr = "[1,2,3,4,5]";
window.x = $.parseJSON(arr);
console.log(x);//cast as an array...
it works even if you have something like
[{"key":"value"}]
However this may NOT work if you have something like this...
[{key:"value"}] // different is the " (double quotes) on key
Turn a string into an array:
var myString = "['boop','top','foo']";
var myArray = JSON.parse(myString)
Just do like this
"sample".split("");
and you'll get
["s", "a", "m", ...]
You cannot cast to Array in JS but a simple ternary operation can do what you want.
var str = 'string';
var arr = (str instanceof Array) ? str : [ str ];
This works for any non-Array object or any primitive value. If you're sure that only actual Array objects and string primitives can be encountered here, the following is a bit faster:
var arr = (typeof str === 'string') ? [ str ] : str;
"1,2,3".split(",")
=> ["1", "2", "3"]
use split()
Val's suggestion also works for strings which have array of arrays
var str = "[[1121,1],[1122,2],[1123,3]]";
var arr = $.parseJSON(str);
console.log(arr); //returns array of arrays
You can also use the following if statement:
if(array instanceof Array != true) {array = [array];}
Array.isArray(foo) || (foo = [foo]);
or if that's not comfortable
foo = Array.isArray(foo) ? foo : [foo];
There is already a proposal for Array.flatten() and usable with babel-preset-stage-2.
const array = ['foo'].flatten()
console.log(array) // ['foo']
const array = [['foo', 'bar']].flatten()
console.log(array) // ['foo', 'bar']