how to change the array elements and get new array in javascript - javascript

I would like to know how to modify the array that contains the path in javascript
how to change the path as shown in expected output
var arr =[
"C:\Users\dc\public\index.js",
"C:\Users\dc\public\javascripts\index1.js",
"C:\Users\dc\public\javascripts\index2.js"
]
Expected Output
[
"/dc/public/index.js",
"/dc/public/javascripts/index1.js",
"/dc/public/javascripts/index2.js",
]

If editing the file paths is not an option, you can use String.raw to accomplish this without having to escape the file paths. Instead of setting the array directly below, I used "push" so that you can use a loop on your own if you get these paths automatically.
var arr = [];
arr.push(String.raw `C:\Users\dc\public\index.js`);
arr.push(String.raw `C:\Users\dc\public\javascripts\index1.js`);
arr.push(String.raw `C:\Users\dc\public\javascripts\index2.js`);
arr = arr.map(a => a.replace("C:\\Users", "").replace(/\\/g, "/"));
// Output
console.log(arr);
//0: "/dc/public/index.js"
//1: "/dc/public/javascripts/index1.js"
//2: "/dc/public/javascripts/index2.js"

First replace the prefix "C:\Users" with empty string to delete them. Then replace the "" character in the resulting string with required "/"
var arr =[
"C:\\Users\\dc\\public\\index.js",
"C:\\Users\\dc\\public\\javascripts\\index1.js",
"C:\\Users\\dc\\public\\javascripts\\index2.js"
];
var pattern = new RegExp("(.+)dc")
arr = arr.map(a => a.replace(pattern, "dc").replace("/\\/g", "\/"));
console.log(arr);

var arr =[
"C:\\Users\\dc\\public\\index.js",
"C:\\Users\\dc\\public\\javascripts\\index1.js",
"C:\\Users\\dc\\public\\javascripts\\index2.js"
];
const outputArr = arr.map(item => {
const splitArr = item.split("\\");
const filterArr = splitArr.slice(2, splitArr.length);
return `\\${filterArr.join("\\")}`;
});
console.log(outputArr);

Related

How to get particular part of string from an array of strings using javascript?

Hi below is array of strings
const arr = [
"list/1/item/1/",
"some-domain/2/item/2/",
"item/3/",
"some-domain/4/item/5/subitem/1/",
]
i have to filter those strings that start with string "item/3/" or ends with string "item/3/"
so from above array expected filtered array is like below,
const filtered_arr = [
"list/1/item/1/",
"some-domain/2/item/2/",
"item/3/",
]
from the filtered array i want to get the number after "/item/". so from above filtered array the expected output is
const arr_ids = ["1", "2", "3"]
what i have tried,
i have used below to match those strings that start or end with /item/3/
const filtered_arr = arr.map(str) => {
return str.match(/item\/[0-9](\/)?$/g);
}
this gives the filtered_arr
const filtered_arr = [
"list/1/item/1/",
"some-domain/2/item/2/",
"item/3/",
]
but how do i map through each array item and get the number after string "/item/".
could someone help me with this. thanks.
Use filter to filter paths either starting or ending in item/\d+/. Then use map to extract the item number from each matching path.
const arr = [
"list/1/item/1/",
"some-domain/2/item/2/",
"item/3/",
"some-domain/4/item/5/subitem/1",
];
var output = arr.filter(x => x.match(/^item\/\d+|\bitem\/\d+\/$/))
.map(x => x.match(/(?<=^item\/)\d+|(?<=\bitem\/)\d+(?=\/$)/)[0]);
console.log(output);
This may help:
const filtered_arr = arr.map(str) => {
const match = str.match(/\/item\/(\d)/);
return(match[1]);
}

How to remove NaN from a string in an array

I have this array that is used by Svg to create a map. It contains one big string. The problem is that there are NaNs in the array and it is not able to read the array properly. How can I remove these NaNs?
Array [
"M214.00002913287273,NaNL214.0000224099021,NaNL214.00002913287273,NaNL214.00002913287273,NaNL214.00011653149096,NaNL214.00011317000562,NaNL214.00011317000562,NaNL214.00000784346574,214.00018930549527L214.0000224099021,NaNL213.999936131779,213.99969560711412L213.999936131779,213.99969560711412L214.00011317000562,NaNL214.00002913287273 ...
]
array = ["M214.00002913287273,NaNL214.0000224099021,NaNL214.00002913287273,NaNL214.00002913287273,NaNL214.00011653149096,NaNL214.00011317000562,NaNL214.00011317000562,NaNL214.00000784346574,214.00018930549527L214.0000224099021,NaNL213.999936131779,213.99969560711412L213.999936131779,213.99969560711412L214.00011317000562,NaNL214.00002913287273"]
you can map this array and use replace for each string
array = array.map(x => x.replace(/NaN/g,''))
array = ["M214.00002913287273,NaNL214.0000224099021,NaNL214.00002913287273,NaNL214.00002913287273,NaNL214.00011653149096,NaNL214.00011317000562,NaNL214.00011317000562,NaNL214.00000784346574,214.00018930549527L214.0000224099021,NaNL213.999936131779,213.99969560711412L213.999936131779,213.99969560711412L214.00011317000562,NaNL214.00002913287273"]
array = array.map(x => x.replace(/NaN/g,''))
document.documentElement.innerHTML = array
you can map over the array & replace the cprrupted strings like this
const corruptedStrings = [
"M214.00002913287273,NaNL214.0000224099021,NaNL214.00002913287273..."
];
const replaceWord = (originalWord, wordToMatch, newValue) => (
originalWord.replace(new RegExp(wordToMatch, 'g'), newValue);
)
const cleanedStrings = corruptedStrings.map(str => replaceWord(str, 'NaN', ''));

Javascript Get all number from array

From Array get only number into a new array or a string
var fetchMIDarray = [
'Corp: nameofthecompany (345961663886)',
'Chain: somerandomname (372395416889)'
]
except result for new array should be:
var fetchnumber =['345961663886','372395416889']
I know how this works for the string but unable to do same for array
code sinppet for string.
var midname='Corp: Best Buy ApplePay/Partsearch (345961663886)';
var matches2 = midname.match(/\d+/);
console.log(matches2);
You can use Array#map.
let arr = ['Corp: nameofthecompany (345961663886)', 'Chain: somerandomname (372395416889)'];
let res = arr.map(x => x.match(/\d+/)[0]);
console.log(res);

How to separate a string as according to a condition, using split?

good morning I have these text strings:
json_schema.account_overview.name
json_schema.no_owned.contact.contact
but now I'm trying to separate according to the string 'json_schema.no_owned', doing like this:
my_string.split ("json_schema.no_owned."). filter (x => x);
but doing a console.log of that result I get this
the first arrangement is fine, since to that same arrangement I can apply another split and I will have again separated by '.'
but the second fix has nothing to do with what I was saying should be after 'json_schema.no_owned.' (note the period at the end)
This way I am trying to do it:
let string ="json_schema.no_owned.contact.contact";
let arrayString = [
'json_schema.no_owned.contact.contact',
'json_schema.account_overview.name'
];
let schema = "";
for(let i in arrayString){
schema = arrayString[i].split("json_schema.no_owned.").filter(x => x);
console.log(schema);
}
I only want to have in an array the elements that are after 'json_schema.no_owned'
Thanks.
You can check if element has "json_schema.no_owned." part at all:
let string ="json_schema.no_owned.contact.contact";
let arrayString = [
'json_schema.no_owned.contact.contact',
'json_schema.account_overview.name'
];
let schema = "";
for(let i in arrayString){
if (arrayString[i].includes("json_schema.no_owned.")) {
schema = arrayString[i].split("json_schema.no_owned.").filter(x => x);
console.log(schema);
}
}
Maybe you can use a short way to do it.
let arrayString = [
'json_schema.no_owned.contact.contact',
'json_schema.account_overview.name'
];
const schemas = arrayString.filter(x => x.includes("json_schema.no_owned."))
.map(x => x.split("json_schema.no_owned.")[1]);

How to compare a part of an array item with a part of an array item from a second array?

If I have two arrays with files
arr1 = ['file1.webp', 'file2.webp', ...];
arr2 = ['file1.jpg', 'file2.png', 'file3.jpg', 'file4.jpg', ...];
how would I check which array items are equal, minus the *.format part?
The idea is that, if there are two equal items, a webp and an alternative source are available. While if an item has no match, no webp source was provided. Both cases would lead to different image handling later on.
I could compare the items inside two arrays like so: let match = arr1.find( val => arr2.includes(val) );
But this compares each entire item. I only want to compare the file names. The formats in which the files were provided need to be cut off, so I get:
arr1 = ['file1', 'file2', ...];
arr2 = ['file1', 'file2', 'file3', 'file4', ...];
I can then filter out all matches between the two arrays. I've been searching for a solution for a real while, but I'm still not sure how to get there.
With a function that trims off the file extension, you can construct a Set of one of the transformed arrays. Then iterate over the other array and check whether its transformed item is in the Set or not:
const arr1 = ['file1.webp', 'file2.webp'];
const arr2 = ['file1.jpg', 'file2.png', 'file3.jpg', 'file4.jpg'];
const transform = str => str.replace(/\.[^.]+$/, '');
const set1 = new Set(arr1.map(transform));
for (const item of arr2) {
if (set1.has(transform(item))) {
console.log('Match for', item);
} else {
console.log('No match for', item);
}
}
You can use filter() with nested some(). To get the file name from complete name use split('.')and get the first element using .split('.')[0]
let arr1 = ['file1.webp', 'file2.webp'];
let arr2 = ['file1.jpg', 'file2.png', 'file3.jpg', 'file4.jpg'];
let res = arr2.filter(a => arr1.some(b => a.split('.')[0] === b.split('.')[0]));
console.log(res)
You could filter by looking to the right side.
const getName = s => s.replace(/\.[^.]+$/, '');
var array1 = ['file1.webp', 'file2.webp'],
array2 = ['file1.jpg', 'file2.png', 'file3.jpg', 'file4.jpg'],
set1 = new Set(array1.map(getName)),
common = array2.filter(s => set1.has(getName(s)));
console.log(common);
write extract method to get value to compare. Just use the extract method in your code. Alternatively, you can build an arr2Obj to not to repeat the searches.
const arr1 = ["file1.webp", "file2.webp"];
const arr2 = ["file1.jpg", "file2.png", "file3.jpg", "file4.jpg"];
const extract = item => item.split(".")[0];
let match = arr1.find(val => arr2.map(x => extract(x)).includes(extract(val)));
console.log(match);
// Alternatively,
const arr2Obj = Object.assign({}, ...arr2.map(x => ({ [extract(x)]: 1 })));
const match2 = arr1.find(val => extract(val) in arr2Obj);
console.log(match2);

Categories

Resources