How to split a string by dash at specific position JavaScript - javascript

I have a dynamically created array as below:
["171281-0-001-1", "171281-0-001-2"]
Basically, I am creating the value based on a very complex function. But that function does not matter here. Basically for example 171281-0-001-1 is made of Account number + id. 171281-0-001 is Account number and 1 is the id.
The number of dashes can be any number but after the last dash it's always id.
How can I differentiate these from my value and assign it into different variables?
Tried:
for (let key in this.your_reference) {
extractedAccountNumber = key.split('-')[0];
extractedId = key.split('-')[1];
}
But since the dashes can be in any number now, the variables have wrong values. Any idea guys? Thanks in advance

You can use map() and split() to take the item from the last array index:
var arr = ["171281-0-001-1", "171281-0-001-2"];
var idList = arr.map(d => {
d = d.split('-');
return d[d.length - 1];
});
console.log(idList);

You could use a regular expression with two groups: one captured group, which matches anything, then match a dash, then another captured group for digits followed by the end of the string:
["171281-0-001-1", "171281-0-001-2"].forEach((str) => {
// first item in the array is the entire match,
// but you only care about the two capture groups, so ignore the first item:
const [,accountNumber, id] = str.match(/(.+)-(\d+)$/);
console.log(accountNumber);
console.log(id);
});

You can use lastIndexOf and substring for that:
var arr = ["171281-0-001-1", "171281-0-001-2"];
var ids = arr.map(d => d.substring(d.lastIndexOf('-') + 1));
console.log(ids);

const arr = ["171281-0-001-1", "171281-0-001-2"];
const accountDetails = arr.map((item) => {
const itemArr = item.split('-');
const accountNumber = itemArr.slice(0, itemArr.length -1).join('-');
const id = itemArr[itemArr.length - 1];
return {id, accountNumber};
});
console.log(accountDetails);

Related

Compare two arrays and remove items with partial match

I need to compare two arrays for PARTIAL / SUBSTRING matches. If these are found, I want the matching items removed from the originalArray or create a new array with all those items that did not have a partial match,
var originalArray = ['www.google.com/opq', 'www.yelp.com/abc', 'www.yahoo.com/klm', 'www.bing.com/xyz', 'www.google.com/124'];
var itemsToBeRemoved = ['google.com', 'yahoo.com'];
// DESIRED ARRAY: An array with items that did not have a partial match. For example:
var cleanArray = ['www.yelp.com/abc', 'www.bing.com/xyz']
It work when its a FULL / EXACT match.
But it is NOT what I need.
function cleanFullMatch(){
// Your main array
var originalArray = ['www.google.com/rugby', 'www.yelp.com/abc', 'www.yahoo.com/tennis', 'www.bing.com/xyz', 'www.google.com/football'];
Logger.log(originalArray);
// This array contains strings that needs to be removed from main array
var itemsToBeRemoved = ['www.google.com/rugby', 'www.yahoo.com/tennis', 'www.google.com/football'];
var cleanObj = {};
itemsToBeRemoved.forEach( e => cleanObj[e] = true);
itemsToBeRemoved.forEach( e => itemsToBeRemoved[e]= true);
var cleanArray = originalArray.filter(function(val){ return !cleanObj [val] })
Logger.log(cleanArray);
}
You can use JavaScript RegExp to create regular expression and array.filter(function) to remove elements that does not match the regex.
Sample Code:
function cleanFullMatch(){
// Your main array
var originalArray = ['www.google.com/rugby', 'www.yelp.com/abc', 'www.yahoo.com/tennis', 'www.bing.com/xyz', 'www.google.com/football'];
Logger.log(originalArray);
// This array contains strings that needs to be removed from main array
var itemsToBeRemoved = ['google.com', 'yahoo.com', 'google.com'];
// loop through itemsToBeRemove
itemsToBeRemoved.forEach(function(rgx){
// convert each element of itemsToBeRemove to regular expression
var re = new RegExp(rgx);
// filter the array by removing the elements that match the regex
// test() method checks if the string matches the regex
originalArray = originalArray.filter( word => !re.test(word));
});
Logger.log(originalArray);
}
Sample Output:
filter out the elements of the originalArray so that none of the itemsToBeRemoved is present in any of the filtered elements.
There are many ways to check whether a substring is included in another string, as others said, like includes, indexOf and RegExp.
You could then iterate through all of these itemsToBeRemoved in different ways. You could, for example, use some:
function cleanFullMatch(){
var originalArray = ['www.google.com/rugby', 'www.yelp.com/abc', 'www.yahoo.com/tennis', 'www.bing.com/xyz', 'www.google.com/football'];
var itemsToBeRemoved = ['google.com', 'yahoo.com'];
var cleanArray = originalArray.filter(element => !itemsToBeRemoved.some(item => element.includes(item)));
console.log(cleanArray);
}
Or, alternatively, every:
var cleanArray = originalArray.filter(element => itemsToBeRemoved.every(item => !element.includes(item)));
As you can see, the filtering process can be reduced to a single line.

Sort array elements on JavaScript

I have an array, each subarray of which contains different positions in different order:
[
["apple(2)", "banana(5)"],
["peach(3)", "banana(1)"],
["apple(1)"]
]
I need to sort it on JavaScript (ES6) and i expect to get an array like this:
[
["apple(2)", "banana(5)", "peach(0)"],
["apple(0)", "banana(1)", "peach(3)"],
["apple(1)", "banana(0)", "peach(0)"]
]
Order of each subarray should be the same. If subarray don't have some position, i need to add it with 0 value. Can i using something like map() or sort() function or need to compare it manually?
Here is functional programming approach, using a Map and reduce:
const data = [['apple(2)', 'banana(5)'],['peach(3)', 'banana(1)'],['apple(1)'],];
// Create a Map with default values for each name, i.e. with "(0)":
let names = new Map(data.flat().map(item => [item.replace(/\d+/, ""), item.replace(/\d+/, "0")]));
let result = data.map(row =>
[...row.reduce((map, item) =>
map.set(item.replace(/\d+/, ""), item), // Overwrite default
new Map(names) // Start with clone of original Map
).values()]
);
console.log(result);
You have to loop over to get the keys used. You then have to loop over a second time to get the fill in the missing keys. There are many ways of doing it, this is one.
var data = [
["apple(2)", "banana(5)"],
["peach(3)", "banana(1)"],
["apple(1)"]
];
// match string and number
var re = /([^(]+)\((\d+)\)/;
// Loop over and find all of the keys
var grouped = data.reduce((info, subset, index) => {
subset.forEach(item => {
// find the key and count
var parts = item.match(re);
// have we seen this key?
if (!info[parts[1]]) {
// if not create an array
info[parts[1]] = Array(data.length).fill(0);
}
// set the key index with the count
info[parts[1]][index] = parts[2];
})
return info;
}, {});
// loop over the groups and fill in the set
Object.entries(grouped).forEach(([key, counts], colIndex) => {
counts
.forEach((cnt, rowIndex) => {
data[rowIndex][colIndex] = `${key}(${cnt})`;
})
});
console.log(data);
First get the unique words. Then traverse array of arrays to check if the word is present or not. If it is not present then make the word according to your condition and if present then put the original word to the tmp array. At last sort it for each iteration. By the way, I used regex replace method to get the word.
const data = [
['apple(2)', 'banana(5)'],
['peach(3)', 'banana(1)'],
['apple(1)'],
];
const words = [...new Set(data.flat().map((x) => x.replace(/[^a-z]/gi, '')))];
const ret = data.map((x) => {
const tmp = [];
const newX = x.map((y) => y.replace(/[^a-z]/gi, ''));
for (let i = 0, l = words.length; i < l; i += 1) {
if (newX.includes(words[i])) tmp.push(x.shift());
else tmp.push(`${words[i]}(0)`);
}
return tmp.sort();
});
console.log(ret);

How to convert comma separated strings enclosed within bracket to array in Javascript?

How to convert below string to array in Javascript? The reason is that I want to take both value separately.
The string is value from an element, when I print it to console I got:('UYHN7687YTF09IIK762220G6','Second')
var data = elm.value;
console.log(data);
You can achieve this with regex, like this for example :
const string = "('UYHN7687YTF09IIK762220G6','Second')";
const regex = /'(.*?)'/ig
// Long way
const array = [];
let match;
while (match = regex.exec(string)){
array.push(match[1]);
};
console.log(array)
// Fast way
console.log([...string.matchAll(regex)].map(i => i[1]))
source
let given_string = "('UYHN7687YTF09IIK762220G6','Second')";
// first remove the both ()
given_string = given_string.substring(1); // remove (
given_string = given_string.substring(0, given_string.length - 1); // remove )
let expected_array = given_string.split(',');
console.log(expected_array);

Array values to a string in loop

I have an object (key value pair) looks like this
I want to get a string of '[100000025]/[100000013]'
I can't use var str = OBJ[0].PC + OBJ[1].PC (which gives me '100000025100000013')
because I need the bracket structure.
The number of items can vary.
Added >> Can it be done without using arrow function?
const string = array.map(({PC}) => `[${PC}]`).join('/')
You could map every string to the string wrapped in brackets, then join that by slashes.
You can use a map() and a join() to get that structure. - this is hte same solution as Puwka's = but without the template literal.
var data = [
{am: 1, ct: "", pc: "1000000025"},
{am: 2, ct: "", pc: "1000000013"}
];
let newArr = data.map(item => "[" + item.pc +"]");
console.log(newArr.join("/")); // gives [1000000025]/[1000000013]
You can always use classic for in loop
let arr = [{PC:'1000'},{PC:'10000'}]
let arrOut = [];
for(let i = 0; i < arr.length; i++) {
arrOut.push('[' + arr[i].PC + ']');
}
now the arrOut is equal ["[1000]", "[10000]"] what we need is to convert it to a string and add '/' between items.
let str = arrOut.join('/');
console.log(str) // "[1000]/[10000]"
So you need a string in the format of: xxxx/yyyyy from a complex object array.
const basedata = [...];
const result = basedata.map( item => `[${item.PC}]` ).join('/')
so i will explain it now. The map function will return a new array with 1 entry per item. I state that I want PC, but i added some flavor using ticks to inject it inbetween some brackets. At this point it looks like: ["[1000000025]","[100000013]"] and then join will join the arrays on a slash, so it will turn into an array.
"[100000025]/[100000013]"
Now, this will expand based on the items in your basedata. So if you have 3 items in your basedata array, it would return:
"[10000000025]/[100000013]/[10000888]"
First if you want to divide the result then it will be better to change it into number and then just do the division.
Example
Number.parseInt("100000025")/Number.parseInt("100000013")
If you want to display it then better to use string interpolation
surround it with back tick
[${[0].PC}]/[${[1].PC}]
Hope this is what are you looking for

Alphabetically sort array with no duplicates

I'm trying to create a function that takes an array of strings and returns a single string consisting of the individual characters of all the argument strings, in alphabetic order, with no repeats.
var join = ["test"];
var splt = (("sxhdj").split(""))
var sort = splt.sort()
var jn = sort.join("")
join.push(jn)
function removeDuplicates(join) {
let newArr = {};
join.forEach(function(x) { //forEach will call a function once for
if (!newArr[x]) {
newArr[x] = true;
}
});
return Object.keys(newArr);
}
console.log(removeDuplicates(join));
I can not get the current code to work
Check out the comments for the explanation.
Links of interest:
MDN Array.prototype.sort.
MDN Set
var splt = ("sxhdjxxddff").split("")
// You need to use localeCompare to properly
// sort alphabetically in javascript, because
// the sort function actually sorts by UTF-16 codes
// which isn't necessarily always alphabetical
var sort = splt.sort((a, b)=>a.localeCompare(b))
// This is an easy way to remove duplicates
// by converting to set which can't have dupes
// then converting back to array
sort = [...new Set(sort)]
var jn = sort.join("");
console.log(jn);
Something like this :) Hope it helps!
const string = 'aabbccd';
const array = string.split('');
let sanitizedArray = [];
array.forEach(char => {
// Simple conditional to check if the sanitized array already
// contains the character, and pushes the character if the conditional
// returns false
!sanitizedArray.includes(char) && sanitizedArray.push(char)
})
let result = sanitizedArray.join('')
console.log(result);
Try this:
const data = ['ahmed', 'ghoul', 'javscript'];
const result = [...data.join('')]
.filter((ele, i, arr) => arr.lastIndexOf(ele) === i)
.sort()
.join('');
console.log(result)
There are probably better ways to do it, one way is to map it to an object, use the keys of the object for the used letters, and than sorting those keys.
const words = ['foo', 'bar', 'funky'];
const sorted =
Object.keys(
([...words.join('')]) // combine to an array of letters
.reduce((obj, v) => obj[v] = 1 && obj, {}) // loop over and build hash of used letters
).sort() //sort the keys
console.log(sorted.join(''))

Categories

Resources