How to convert 'string of array objects' to an array in react? - arrays

I have researched a few questions on StackOverflow but couldn't find a relevant answer.
I have a string of array like this:
"[{"insert":"Test"},{"insert":"\n","attributes":{"header":1}},{"insert":"Asdasfff"},{"insert":"\n","attributes":{"list":"bullet"}},{"insert":"Asadsf"},{"insert":"\n","attributes":{"list":"bullet"}},{"insert":"Sfsfsft"},{"insert":"\n","attributes":{"header":2}},{"insert":"Make"},{"insert":"\n","attributes":{"list":"unchecked"}},{"insert":"Back"},{"insert":"\n","attributes":{"list":"checked"}},{"insert":"Ban"},{"insert":"\n","attributes":{"list":"unchecked"}},{"insert":"Fg"},{"insert":"\n","attributes":{"list":"checked"}}]"
and I need to convert it to an array as shown below:
I tried JSON.parse() but it didn't work!

It is because of the \n in your JSON. Here an explanation: https://stackoverflow.com/a/5191059/11749096
function jsonEscape(str) {
return str.replace(/\n/g, "\\\\n").replace(/\r/g, "\\\\r").replace(/\t/g, "\\\\t");
}
var data = `[{"insert":"Test"},{"insert":"\n","attributes": 0}]`;
var dataObj = JSON.parse(jsonEscape(data));
console.log(dataObj);

You have not a string of array, the first and the last double quote must be one quote in your case because when you stringify an array it works like this :
const goo = [{"insert":"Test"},{"insert":"\n","attributes":{"header":1}}]
to stringify it :
JSON.stringify(goo)
'[{"insert":"Test"},{"insert":"\n","attributes":{"header":1}}]'
in this case your parse works like :
JSON.parse(foo)
0: {insert: 'Test'}
1: {insert: '\n', attributes: {…}}
length: 2
[[Prototype]]: Array(0)

Related

TS map list of string dates to list of string years

I have a list of dates in string format, like this:
0: "2020-07-10T00:00:00"
1: "1999-01-01T00:00:00"
2: "2020-06-16T00:00:00"
I need to map it in such a way, so I will have a list of year strings- like this:
0: "2020"
1: "1999"
2: "2020"
My way of thinking is trimming the start of the string, then appending it to the new list of years.
What is the most efficient way to do this?
I would use map to transform your given array. Each element needs to be split by - and then use substr(0, 4) to get the first 4 chars, which are the year.
const myArr = ["2020-07-10T00:00:00", "1999-01-01T00:00:00", "2020-06-16T00:00:00"];
const result = myArr.map(v => v.substr(0, 4));
console.log(result)
Use the Date#getFullYear method.
["2020-07-10T00:00:00", "1999-01-01T00:00:00", "2020-06-16T00:00:00"]
.map(date => new Date(date).getFullYear())

Angular5 - Compare Arrays and return matches

I need to compare two arrays and return the matches:
Array1
(13) ["0:EQSOLREENVIO", "1:EQPER", "2:EQCAN", "3:EQRECHKODOC", "4:EQAUS,EQCDE,EQDDE,EQINACCE,EQVAC", "5:EQINDEV", "6:EQCAMBIODI,EQENV,EQFECHA,EQFIESTA,EQINCITRASP", "7:EQENT", "8:EQDEV", "9:EQRCH", "10:EQADMIPDV", "11:EQCRE,EQRETENER", "12:EQRECOOFI"]
0: "0:EQSOLREENVIO"
1: "1:EQPER"
2: "2:EQCAN"
3: "3:EQRECHKODOC"
4: "4:EQAUS,EQCDE,EQDDE,EQINACCE,EQVAC"
5: "5:EQINDEV"
6: "6:EQCAMBIODI,EQENV,EQFECHA,EQFIESTA,EQINCITRASP"
7: "7:EQENT"
8: "8:EQDEV"
9: "9:EQRCH"
10: "10:EQADMIPDV"
11: "11:EQCRE,EQRETENER"
12: "12:EQRECOOFI"
length: 13
__proto__: Array(0)
Array2
(3) ["11", "0", "5"]
0: "11"
1: "0"
2: "5"
length: 3
__proto__: Array(0)
What I have tried:
const orderStatusCodes = this.orderInProgressCmsModel.orderStatusCodes.split("/");
const orderGroupsEditables = this.orderInProgressCmsModel.orderStatusLogEditables.split(",");
let groupFound = '';
const groupFound2 = [];
orderGroupsEditables.forEach((element2) => {
orderStatusCodes.forEach((element) => {
if (element.indexOf(element2) >= 0){
groupFound = element.split(":")[1];
groupFound2.push(groupFound);
}
});
});
Result:
(4) ["EQCRE,EQRETENER", "EQSOLREENVIO", "EQADMIPDV", "EQINDEV"]
0: "EQCRE,EQRETENER"
1: "EQSOLREENVIO"
2: "EQADMIPDV"
3: "EQINDEV"
length: 4
__proto__: Array(0)
When the numbers match from each array I need the code returned. I have been able to do this with the code I show but I would like to know if theres an easier way like using filter or something similar?
One thing to note is that depending on how big the arrays are, you might want to have a more performant algorithm. The solution presented in the question and the one supplied by #Mohammed Mortaga will loop through the second array for every element in the first array (in big O notation, that would be O(n*m)). This is doing a lot more work than is needed. You really only need to loop through each array a single time (in big O notation, that would be O(n+m)).
You can create a lookup table by looping through array1 that you could then use to lookup if the id exists (and readily have access to the corresponding code):
const regex = /^([^:]*):(.*)/;
const lookup = array1.reduce((acc, val) => {
const [, id, code] = regex.exec(val);
acc[id] = code;
return acc;
}, {});
Once you have your lookup table it is constant time complexity to get the code that corresponds to each element in your array2 (meaning for each item we don't need to search for a match, we can know in constant time if there is a match or not). Here you could use reduce:
const codes = array2.reduce((acc, id) => {
const code = lookup[id];
if (code) {
acc.push(code);
}
return acc;
}, []);
or you could use a one-liner:
const codes = array2.filter(id => lookup[id]).map(id => lookup[id]);
The one-liner would be slightly less performant because it is doing two looping operations, but that is relatively minor if the array is pretty small in length (and the big O notation would still be the same but the readability is increased).
Yes, you can achieve this using a single filter function like so:
const array1 = ["0:EQSOLREENVIO", "1:EQPER", "2:EQCAN", "3:EQRECHKODOC", "4:EQAUS,EQCDE,EQDDE,EQINACCE,EQVAC", "5:EQINDEV", "6:EQCAMBIODI,EQENV,EQFECHA,EQFIESTA,EQINCITRASP", "7:EQENT", "8:EQDEV", "9:EQRCH", "10:EQADMIPDV", "11:EQCRE,EQRETENER", "12:EQRECOOFI"];
const array2 = ["11", "0", "5"];
const result = array1.filter(e => array2.indexOf(e.match(/\d+/)[0]) > -1); // ["0:EQSOLREENVIO", "5:EQINDEV", "11:EQCRE,EQRETENER"]
In short, this code iterates over the first array extracting the digits and checks if they exist or not in the second array.
Hope this helps!

How to push object into an array? in Angular 7

I am pushing an object into an array but cannot do it?
I'm doing it like this
this.passData = this.tribeForm.value;
var id = {"tribe_id": 1}
this.passData.push(id)
This is the value in the tribeForm
I also tried
var id = {tribe_id: 1}
and
this.passData.splice(0,0, id)
and
this.passData = Array.prototype.slice(id)
and
this.passData.concat(id)
but it all ends up with
TypeError: this.passData.push/splice/concat is not a function
The question is not that clear, But I understood you are manipulating form data, value of form data returns an Object, Not an array. Objects in JavaScript are represented as key-value pairs, (or attribute-value) pairs.
Example :
var object = {
name : "Jhon",
grade : 12,
gpa : 8.12
}
It is just a collection of key-value pairs, push(), concat() and other methods are supported only for Arrays not for Objects. You can achieve whatever you want simply by creating a new key/attribute and assigning the value to it.
this.passData = this.tribeForm.value
this.passData['tribe_id'] = 1
//or, Objects can also contain nested object
this.passData['someKey'] = {'tribe_id' : 1}
You can create an empty array and push objects to it
Example :
var exampleArray = []
exampleArray.push({'tribe_id' : 1})
Now, it works because exampleArray is an Array not JS object.
Thanks for A2A
First, you need to understand the error:
TypeError: this.passData.push/splice/concat is not a function
Push/splice/concat is functions for Array and because of that the console is yelling at you that the passData is not an Array.
Make sure your passData is an Array and you will able to do so.

Ruby: convert string to array

a = IO.readlines('uniqID.txt')
puts id = a[0]
id = ["Gh089k" , "HG987"] #getting value from txt file
id.class #String
id.push("GD977")
How to convert the above string into array. so that I use method like push. Here id is string looks like an array
Error: undefined method `push' for "[\"Gh089k\", \"HG987\"]":String (NoMethodError)
It looks like a JSON string. You can parse json string to get the desired result.
require 'json'
JSON.parse("[\"Gh089k\", \"HG987\"]") # => ["Gh089k", "HG987"]
Here:
id = JSON.parse(a[0])
Hope it helps !

Fastest way to parse text from an array

I am trying to parse an array of items, each of which is structured like below:
[0x6100000b2480 - Message: Phlare, ID: 92329382, Sender: 2077303954, Timestamp: 1505263276721]
But I am just trying to get the value after "Sender:" so in this case "2077303954". But I will be iterating through a list of these, parsing the value out of each array index.
Assuming "," only appears between values, separate them into pieces using split:
let arr = str.characters.split(separator: ",").map(String.init)
println(arr) // [0x6100000b2480 - Message: Phlare, ID: 92329382, Sender: 2077303954]
You can then split the strings in the resulting array again on ":" to get an array of alternating keys values.
Or perhaps the input was already an array?
Here's an example:
var resultingDictionary = [String:String]()
var stringArray = ["0x6100000b2480 - Message: Phlare", "ID: 92329382", "Sender: 2077303954", "Timestamp: 1505263276721:"]
for eachString in stringArray
{
let arr = eachString.characters.split(separator: ":").map(String.init)
resultingDictionary[arr[0]] = arr[1]
}
print("resulting dictionary is \(resultingDictionary)")
The same concept should work with NSString's componentsSeparatedByString (now known as components(separatedBy: ",").

Resources