How can I extract an array of substring via regex in nodes? - javascript

I have a string var whose value is (1,2)(3,4) and I'd like to extract an array [[1,2],[3,4]] from it. The solution I have is to use str.match but I haven't figured out how to extract the array.
I have tried:
> '(1,2)(3,4)'.match(/([\d]+),([\d])*/)
[ '3,2', '3', '2', index: 1, input: '(3,2)(4,5)', groups: undefined ]
The result is not what I want. So what should I do with the regex for that?

You need to use /(\d+),(\d+)/g or - to only get those inside parentheses - /\((\d+),(\d+)\)/g and get the results using RegExp#exec in a loop:
var s = '(1,2)(3,4)', m, results=[];
var rx = /(\d+),(\d+)/g;
while(m=rx.exec(s)) {
results.push([m[1], m[2]])
}
console.log(results);
Or, with matchAll if you target the latest JS environments:
const s = '(1,2)(3,4)', rx = /(\d+),(\d+)/g;
const results = [...s.matchAll(rx)];
console.log(Array.from(results, x => [x[1],x[2]]))

There's the other way around, without using RegExp, just in case:
const src = '(1,2)(3,4)',
result = src
.slice(1,-1)
.split(')(')
.map(s => s.split(','))
console.log(result)
.as-console-wrapper{min-height:100%;}

Related

Javascript join array with brackets

In javascript I need to join an array into a string with brackets. For example ['abc', 'yte', 'juu'] => (abc)(yte)(juu). I need the fastest and cleanest way to do this. I tried using the array join operator but it doesnt work on the first and last element.
You can do it with template literals. Use join() with )( separator, and wrap the result with ():
const data = ['abc', 'yte', 'juu'];
const result = `(${data.join(')(')})`;
console.log(result);
Thinking "I need the fastest and cleanest way to do this." is often not ideal. In most cases what people want is the most readable and understandable way to implement a solution.
I quite like the following. Where we first bracket each item in the array with map and then join the items with no delimiter:
const data = ['abc', 'yte', 'juu'];
let brackets = data.map(x => "(" + x + ")");
let result = brackets.join("")
console.log(result);
That of course takes two passes over the array. If you really must have the fastest solution just use a for loop:
const data = ['abc', 'yte', 'juu'];
let result = "";
for (let item of data) {
result += "(" + item + ")";
}
console.log(result);
In order to reduce an array to a single value (be that an object, array, string, number, ...) Javascript has the Array.prototype.reduce method, which achieves the desired result in a single loop and line:
console.log(['abc', 'yte', 'juu'].reduce((a,v)=>`${a}(${v})`,''))
const list = ['abc', 'yte', 'juu'];
const result = list.map(value => `(${value})`).join("");
console.log(result);

How do I filter certain items in an array

I have this array
let arr = [ 'file_1.jpg' , 'file_2.png', 'file_3.pdf', 'file_4.html', 'folder.db' ]
I want to filter the files that has .jpg and .png on it.
arr.filter() // desired output: [ 'file_1.png','file_2.png' ]
arr.filter(link => link.endsWith(".png") || link.endsWith(".jpg"));
Filter with a RegExp:
const arr = [ 'file_1.jpg' , 'file_2.png', 'file_3.pdf', 'file_4.html', 'folder.db' ];
const pattern = /\.(png|jpg)$/; // string should end with .png or .jpg
const result = arr.filter((name) => pattern.test(name));
console.log(result);
const result = arr.filter( link => link.endsWith(".png") || link.endsWith(".jpg"));
Filter Function
The filter function accepts one callback function which returns a boolean for each item of the list.
So you could create a function that is using a regular expression to check if a string is a png or jpg.
Creating the filtering expression
In JavaScript regular expressions look like this: //
The dot is a special character (match any character) so you need to escape it: /\./
To match a string from a collection of strings you can use () and separate the options using a pipe (|): /\.(jpg|png)/
You can check if that is the end of text by adding $ at the end: /\.(jpg|png)$/
Then using the test function you can check if a string matches your expression.
arr.filter(isJPEG);
function isJPEG(text) {
return /\.(jpg|png)$/.test(text);
}
Working Example
var arr = ['file_1.jpg', 'file_2.png', 'file_3.pdf', 'file_4.html', 'folder.db'];
var filteredList = arr.filter(isJPEG);
console.log(JSON.stringify(filteredList));
function isJPEG(text) {
return /\.(jpg|png)$/.test(text);
}

How to ouput value of matching case in an array

I have an array
var hashtags = [ '#hr', '#acc', '#sales', '#hr' ];
I understand that to look for a specified matching value I'd have to use this
if (hashtags.indexOf("#hr") > -1)
// output value
But how do I output ALL the matching values that match the condition?
You can use Array#filter and equality comparison to get all the occurrences of your word in the given array.
var hashtags = [ '#hr', '#acc', '#sales', '#hr' ];
var result = hashtags.filter( word => word === '#hr');
console.log(result);
You can use Array#filter and check inside the condition. Also instead of indefOf you can use Array#includes function.
const hashtags = [ '#hr', '#acc', '#sales', '#hr' ];
const filteredHashtags = hashtags.filter(item => item.includes('#hr'));
console.log(filteredHashtags);
string [] arr = {"One","Two","Three"};
var target = "One";
var results = Array.FindAll(arr, s => s.Equals(target));

How to extract value from an Array in 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

Remove last letter from map value

So I'm getting this from backend:
{"Item":{"userEmail":"b","Username":"bUsername","Push":"sdsdsd","Password":"sdsds","Buddy":{"datatype":"SS","contents":{"Drake":"Drake","Ola":"Ola","b":"b","d":"d"}}}}
I use Object.Keys to narrow down the contents to:
Drake,Ola,b,d
Which I then map to give:
[{"id":"Drake"},{"id":"Ola"},{"id":"b"},{"id":"d"}]
Which is then used on my Angular Front-end as .id. I want to remove the last letter from each value i.e leaving Drak,Ol etc. I've tried many ways but have failed, how can I achieve this please so that the id has those values?
EDIT
I also want to now get that value that was cut AND add it such that the end product will be [{"id":"Drak",valueThatWasCut:"e"}]
You could iterate the object's keys and build with the short string a new object.
var data = {"Item":{"userEmail":"b","Username":"bUsername","Push":"sdsdsd","Password":"sdsds","Buddy":{"datatype":"SS","contents":{"Drake":"Drake","Ola":"Ola","b":"b","d":"d"}}}},
ids = Object.keys(data.Item.Buddy.contents).reduce(function (r, k) {
var n = k.slice(0, -1);
return n ? r.concat({ id: n }) : r;
}, []);
console.log(ids);
Perhaps something like :
var arr = [{"id":"Drake"},{"id":"Ola"},{"id":"b"},{"id":"d"}];
var result = arr.map(x => x.id.slice(0,-1));
console.log(result); // [ 'Drak', 'Ol', '', '' ]
Create a temporary contents object and change in that.
Then just set this in the original object. ES6 spread operators would save the rest of data without respecifying all keys and values.
let items = {"Item:{"userEmail":"b","Username":"bUsername","Push":"sdsdsd","Password":"sdsds","Buddy":{"datatype":"SS","contents":{"Drake":"Drake","Ola":"Ola","b":"b","d":"d"}}}};
let contents = items.Item.Buddy.contents;
let contentsNew = Object.keys(contents).map((content) => {
return {[content.substring(0, content.length-1)]: content.substring(0, content.length-1), valueThatWasCut: content[content.length-1]};
});
items = {...items, Item: {...items.Item,Buddy:{...items.Item.Buddy,contents: contentsNew}}};
console.log(items);

Categories