Javascript Get all number from array - javascript

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);

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 change the array elements and get new array in 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);

change format of a array javascript

How can I change the format of the array? the idea is to place the array2 equal to the array1, I mean the format of square brackets and commas.
that is, change the ":" with "," and the {} with []
var array1=[["Sep",687918],["Nov",290709],["Dic",9282],["Ene",234065]]
var array2=[{"Sep":687918},{"Nov":290709},{"Dic":9282},{"Ene":348529}]
The most appropriate way to do this is probably using the map() method. Using this, you're constructing a new array by manipulating each item of an original array. Learn more here.
var array2=[{"Sep":687918},{"Nov":290709},{"Dic":9282},{"Ene":348529}];
var array1 = array2.map(function (item) {
var key = Object.keys(item)[0];
var value = item[key];
return [key, value];
});
console.log(array1);
// returns [["Sep", 687918], ["Nov", 290709], ["Dic", 9282], ["Ene", 348529]]
This work for you?
var array1=[["Sep",687918],["Nov",290709],["Dic",9282],["Ene",234065]];
var array2 = {};
array1.forEach(function(element){
array2[element[0]]=element[1];
});
"I mean the format of square brackets and commas"
Square brackets says, that it is an array, and array elements should be separated by commas. Actually, you want to convert the array of arrays to the array of objects. Here is short ES6 solution:
var array1 = [["Sep",687918],["Nov",290709],["Dic",9282],["Ene",234065]];
var newArray = [];
array1.forEach(item => newArray.push({[item[0]]: item[1]}))
console.log(newArray)
You can do this by using the array .reduce method:
var array1=[["Sep",687918],["Nov",290709],["Dic",9282],["Ene",234065]]
var array2 = array1.reduce((arr2, current) => {
arr2.push({[current[0]]: current[1]});
return arr2
}, []);
console.log(array2)

Concatenate array into string

I have this:
var myarray = [];
myarray ["first"] = "$firstelement";
myarray ["second"] = "$secondelement";
And I want to get the string:
"first":"$firstelement","second": "$secondelement"
How can I do it?
What you have is invalid (even if it works), arrays don't have named keys, but numeric indexes.
You should be using an object instead, and if you want a string, you can stringify it as JSON
var myobject = {};
myobject["first"] = "$firstelement";
myobject["second"] = "$secondelement";
var str = JSON.stringify(myobject);
console.log(str)
First of all, you'd want to use an object instead of an array:
var myarray = {}; // not []
myarray ["first"] = "$firstelement";
myarray ["second"] = "$secondelement";
The easiest way, then, to achieve what you want is to use JSON:
var jsonString = JSON.stringify(myarray);
var arrayString = jsonString.slice(1, -1);
JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified, or optionally including only the specified properties if a replacer array is specified.
var myarray = {};
myarray ["first"] = "$firstelement";
myarray ["second"] = "$secondelement";
console.log(JSON.stringify(myarray));
Use JSON.strinify()
JSON.stringify(item)

Match two Arrays as Object of Array

I have two arrays and I need to make it as object of array
var arr1 = [1,2,3,4,5]
var arr2 = [a,b,c]
Is there any possibility to change the array to this format[a,{1,2,3,4,5}],[b,{1,2,3,4,5}],[c,{1,2,3,4,5}]
Could someone help me?
Try this code:
var arr1 = [1,2,3,4,5];
var arr2 = ['a','b','c'];
var result = arr2.reduce(function(obj, item) {
obj[item] = arr1.slice(); // or = arr1 to keep the reference
return obj;
}, {});
console.log(result); // {"a":[1,2,3,4,5],"b":[1,2,3,4,5],"c":[1,2,3,4,5]}
You have 2 cases:
To create clones of the array use result[item] = arr1.slice();
To keep the reference to the same array use result[item] = arr1;
Check more about the reduce() method.
I am assuming you need a object like this
{"a":[1,2,3,4,5],"b":[1,2,3,4,5],"c":[1,2,3,4,5]}
So you can do it like this.
var arr1 = [1,2,3,4,5]
var arr2 = ["a","b","c"];
var result={}
arr2.map(function(k){
result[k]=arr1;
})
console.log(result);
But here I am giving values of keys as arr1 reference so if arr1 will change value of keys in result will also change.
Is there any possibility to change the array to this
formate[a,{1,2,3,4,5}],[b,{1,2,3,4,5}],[c,{1,2,3,4,5}]
This is neither an array format nor a valid JSON literal, so this format could only be a string.
Assuming that you are looking for a string in the format you have specified
var output = "[" + arr2.map(function(value){return value+",{" + arr1.join(",") + "}"}).join("],[") + "]";
Use forEach to iterate through List and get your desired result.
var arr1 = [1,2,3,4,5];
var arr2 = ['a','b','c'];
var result = {} // Result: Object of Array
arr2.forEach(function(val, index) {
result[val] = arr1;
})
I hope this is easy to understand :)

Categories

Resources