Cast string as array - javascript

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']

Related

How to convert JavaScript object into LITERAL string?

If I have the object literal:
{a: "hello"}
Is there a Javascript function to convert this object into a literal string, so that the output would be the literal syntax:
'{a: "hello"}'
With JSON.stringify the output would be
'{"a": "hello"}'
You can do it with JSON.stringify and then with String.replace like follows:
var jsObj =
{
abc: "hello",
bca: "allo",
cab: "dd:cc",
d: ["hello", "llo", "dd:cc"],
e: {abc: "hello", bca: "allo", cab: "dd:cc"}
};
function format(obj)
{
var str = JSON.stringify(obj, 0, 4),
arr = str.match(/".*?":/g);
for(var i = 0; i < arr.length; i++)
str = str.replace(arr[i], arr[i].replace(/"/g,''));
return str;
}
console.log(format(jsObj));
JavaScript has no built-in functions that will convert an object to a string representation of it which either:
Uses identifiers instead of strings for property names
Represents the original syntax used to create the object
You could write your own function for the former (at least when the property name can be represented as a literal) but the latter is impossible as JavaScript stores no information about the source code used to create the object in the first place.
Ok just for fun...roll your own?
const stringify = (obj) => {
// Iterate over keys, reducing to a string
let str = Object.keys(obj).reduce((acc, cur) => {
let next = `${cur}: "${obj[cur]}"`;
return acc
? `${acc}, ${next}`
: `{${next}`;
}, '');
// Return, appending final '}'
return `${str}}`;
}
document.write(stringify({
foo:1,
bar:'seat'
}));
That said, your exact requirements aren't clear so I'm not sure this will meet them. But it might be a starting point if there's no native solution that works.
It does convert it to the literal syntax. You are able to create objects with multiple forms of syntax. Both of the following object declarations are valid:
var a = {a: "a"}
var b = {"b": "b"}
If you want to remove the "" around the key you should be able to match them with the following regex /\"(.*?)\":/g and replace them with something like this:
function reformat(str) {
var myRegexp = /\"(.*?)\":/g;
match = myRegexp.exec(str);
while (match != null) {
str = str.replace(match[0], match[1] + ":");
match = myRegexp.exec(str);
}
return str;
}
Hope that helps :)

deleting a object of an Array based on property of the object

I have an Array like this: var obj = [{x:4, y:5}, {x:6, y:2}, ...] and I'm trying to delete one of the inside objects (properties) based on the x.
this is How I'm trying to do this:
obj.forEach(function (child){
if(child.x === 4){
obj.destroy(child)
}
});
But it's not working and i get
obj.destroy is not a funtion
I also tried obj.splice(child) but it just mess up the array. so what am doing wrong here?
Also is there a better way to do this by not having to loop through all of Array property every time?
You can just use filter on the array: e.g.
let arrayToFilter = [ {x:4, y:5}, {x:6, y:2}];
const valueToFilter = 4;
var filteredArray = arrayToFilter .filter((o) => {
return o.x !== valueToFilter;
});
console.log(filteredArray);
forEach() works on array.
If obj is an array, you can simply use filter() to remove the unwanted object from the array:
var obj = [{x:4, y:5}, {x:6, y:2}]
obj = obj.filter(c => c.x !== 4)
console.log(obj);
You perhaps, have an array as obj because the one you posted in the question is simply invalid syntax.
Moreover, you can use Array#findIndex to get the index of the matching element first, and then splice that index from the array.
var obj = [{x:4, y:5}, {x:6, y:2}];
var index = obj.findIndex(item => item.x === 4);
obj.splice(index, 1);
console.log(obj);
i'm assuming your trying to filter out objects in an array which have an x that matches a given value. If thats the case, you should probably use the filter method.
So assuming thats what you mean you could do the following
obj = obj.filter(function (child){
if(child.x !== 4){
return obj
}
});
// shorter
obj = obj.filter( child => child.x !== 4 );
In this case, only the objects which do not have the value of 4 will be available to you in the obj variable. And all other objects (assuming there are no other references in your code) will be garbage collected.

Filter matched items in an array of string with another (key,value) objects in angularjs

I am using angular as front end. I have below array of strings. I want to filter this "array" with matched keys of another "(key,value) objects".
String Array:
var stringArr = ["vijay-1110","viki-1100","ram-2110","mark-2100"]
(key,value) Objects:
var obj = {"viki-1100":6,"mark-2100":2}
To return only the non matched keys from stringArr,So desired output:
var result = ["vijay-1110","ram-2110"]
I haven tried the below code which doesnot return the desired output?
var filterFunction = function(stringArr,obj){
if(angular.equals({}, obj)){
return stringArr;
}
else{
_.each(stringArr,function(input,index){
Object.keys(obj).forEach(function(key) {
if(input === key){
stringArr.splice[index,1];
}
});
});
return stringArr;
}
this wont filter the stringArr, It always return all the results in stringArr?
Try
stringArr.filter( s => typeof obj[s] != "undefined" )
Edit
I realized that OP is looking for the opposite of my answer, so simply replaced != with ==
stringArr.filter( s => typeof obj[s] == "undefined" )
Try the following way:
var stringArr = ["vijay-1110","viki-1100","ram-2110","mark-2100"]
var obj = {"viki-1100":6,"mark-2100":2}
var result = stringArr.filter(function(item){
return !(item in obj)
});
console.log(result)
You can use in to check if a key exist inside an object. Use array#filter to iterate through your array and for each value return the non-existent value.
var stringArr = ["vijay-1110","viki-1100","ram-2110","mark-2100"];
var obj = {"viki-1100":6,"mark-2100":2};
var result = stringArr.filter(name => !(name in obj));
console.log(result);
The code below works and manage the case where obj is an empty object. Object.keys(...).length is here to check if obj is an empty object or not
var stringArr = ["vijay-1110","viki-1100","ram-2110","mark-2100"];
var obj = {"viki-1100":6,"mark-2100":2};
var filterFunction = function(stringArr,obj){
return stringArr.filter(str => Object.keys(obj).length === 0 || obj[str] );
}
console.log(filterFunction(stringArr, obj));
console.log(filterFunction(stringArr, {}));

JavaScript How to take all strings from an array and print them using filter?

If you don't understand the question, please see the code, i hope you will understand.
I want to take all strings that are in array, where in the same array have numbers for example and Booleans
I have an array in JavaScript
var names = ['a','v','c','Earth',2,3,4,12,3,3434,true,false,'Fire'];
How to check how many strings are in the array and print then using filter?
I am trying to learn how to use filter.
Just use typeof operator:
var names = ['a','v','c','Earth',2,3,4,12,3,3434,true,false,'Fire'];
var onlyStringValues = names.filter(function (value) {
return typeof value === 'string';
});
With filter in ES6 :
var names = ['a','v','c','Earth',2,3,4,12,3,3434,true,false,'Fire'];
var strings = names.filter(value => typeof value === 'string');
console.log(strings); // [ 'a', 'v', 'c', 'Earth', 'Fire' ]
Try this!
function stringFilter(arr) {
var filtered = [];
for(var i = 0; i < arr.length; i++){
if(typeof(arr[i]) === 'string') {
filtered.push(arr[i]);
}
}
return filtered;
}
You can use typeof condition to select all strings, these can then be added to a new array, of which you can get the length and also print them out if you like.
For more information go here:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/typeof

how to remove redundant array objects

I need to remove all the duplicate elements, for example:
var arr = [
{'seriesIndex':1,pointIndex:0},
{'seriesIndex':1,pointIndex:1},
{'seriesIndex':0,pointIndex:0},
{'seriesIndex':1,pointIndex:0},
{'seriesIndex':1}
]
How to remove redundant (duplicate) array objects from an array?
My expected output is:
arr = [
{'seriesIndex':1,pointIndex:0},
{'seriesIndex':1,pointIndex:1},
{'seriesIndex':0,pointIndex:0},
{'seriesIndex':1}
]
How to achieve this?
In vanilla Javascript, I'd suggest to keep track of the encountered composite keys while iterating on the list in a .reduce() method. The test on prv.key[key] is O(1) (hashtable lookup), so this algorithm is O(n).
var arr = [
{seriesIndex:1, pointIndex:0},
{seriesIndex:1, pointIndex:1},
{seriesIndex:0, pointIndex:0},
{seriesIndex:1, pointIndex:0},
{seriesIndex:1}
];
arr = arr.reduce(function(prv, cur) {
var key = cur.seriesIndex + '/' + cur.pointIndex;
if(!prv.key[key]) {
prv.key[key] = true;
prv.res.push(cur);
}
return prv;
}, {key: {}, res: []}).res;
console.log(arr);
I use library, which has rich API - lodash
With lodash it looks like :
_.uniqWith(arr, _.isEqual)
It is simple and short
Link to library https://lodash.com/
By an invention of Object.prototype.compare() you may do like this
Object.prototype.compare = function(o){
var ok = Object.keys(this);
return typeof o === "object" && ok.length === Object.keys(o).length ? ok.every(k => this[k] === o[k]) : false;
};
var arr = [{'seriesIndex':1,pointIndex:0},
{'seriesIndex':1,pointIndex:1},
{'seriesIndex':0,pointIndex:0},
{'seriesIndex':1,pointIndex:0},
{'seriesIndex':1}
],
result = arr.reduce((res,obj) => res.length === 0 ? res.concat(obj)
: !!res.find(o => obj.compare(o)) ? res
: res.concat(obj),[]);
console.log(JSON.stringify(result,null,2));

Categories