I have 2 Javascripts Array
var array1 = ["Mergen Morry","Dash Borad","Mergen Xss"];
var array2 = ["02111356","4458763","02111356"];
I want the output to be like this
Mergen Morry – 02111356 : data uploaded
Dash Borad - 4458763 : data uploaded
Mergen Xss – 02111356 : id already registered
I was thinking using join(), but as I recall this is 2 array, and using concat() are out of question, and maybe was thinking using map() or forEach(), but I still don't get how.
Edit : I'm sorry, the output should be string not array.
You could take an object for keeping seen id and return appropriate comments for mapping strings.
const
names = ["Mergen Morry", "Dash Borad", "Mergen Xss"],
ids = ["02111356", "4458763", "02111356"],
result = names.map(
(seen => (s, i) => `${s} - ${ids[i]} : ${ seen[ids[i]]
? 'id already registered'
: (seen[ids[i]] = true, 'data uploaded') }`)
({})
).join('\n');
console.log(result);
#Nina Scholz answer is pretty good, and here the another way you could have json with all its content instead.
var array1 = ["Mergen Morry","Dash Borad","Mergen Xss"];
var array2 = ["02111356","4458763","02111356"];
var res = array1.map((item,index)=>{
return {name:item,id:array2[index]}
},[]);
// Now that you have an array with Id and namne, you could loop throw each array and display the data
console.log(res)
Related
I was trying to compare 2 different api calls from which i am able to make out 2 different arrays of ids , So i am trying to filter out the ids which already exist in array2 , and for the remaining ids i am trying to set the state , could anyone help me with it ?
code so far :
const [ prevAdmins , setPrevAdmins ] = useState<any>([]);
const [options, setOptions] = useState([{value: "", label: ""}]);
//API 1 CALL
get_user_groups({bot_id:params.botid , group_id:params.userid}).then((res) => {
setDetails(res?.data?.data[0]);
setGroupName(res?.data?.data[0].name)
let prevAdmins: any = [];
res?.data?.data[0]?.join_details.map((prevJoinee , idx) => {
prevAdmins.push(prevJoinee.user_id)
setPrevAdmins(prevAdmins)
})
});
//OUTPUT FOR API 1 "prevAdmins": ['61dfcfb71f492f4f4f589e93', '61dedd23bd15322626dd7539']
//2nd API CALL :
get_followers({bot_id:params.botid}).then((res) => {
if(res.data.data){
let option: any = [];
let allAdmins: any = [];
res.data.data.map((admin, index) => {
allAdmins.push(admin._id);
if(!prevAdmins.includes(allAdmins)){
option.push({value: admin._id, label: admin.displayName})
}
})
setOptions(option);
}
})
//OUTPUT FOR API 2 : ['61dfd02a1f492f4f4f589f00', '61dfcfb71f492f4f4f589e93', '61dedd23bd15322626dd7539']
Now what i am trying is to exclude the ids which is already present in Array 1 and setOptions should store the ids which are not excluded.
Regards !
If you want to get the unique values form your api calls, You can use Set instead of an array.
Please refer: https://www.javatpoint.com/typescript-set
You can use spread operator to combine two arrays and then convert it to Set and make an array from that Set. It will be unique.
roughly you can do something similar to this approach.
let array1 = [1,2,4]
let array2 = [4,3,5,6]
let combinedArray = [...array1, ...array2]
let arraySet = new Set(combinedArray)
let uniqueArray = Array.from(arraySet)
console.log(uniqueArray)
spread operator will combine two arrays but it will have duplicate values too.
when you convert it into Set, it will remove any duplicate values.
Then you can simply generate an array from that Set variable.
You can do this to make it short too.
let uniqueArray = Array.from(new Set([...array1, ...array2]))
after you have the unique array you can simply set state with the uniqueArray variable.
In your case:
if you are getting these two arrays.
let arr1 = ['61dfcfb71f492f4f4f589e93', '61dedd23bd15322626dd7539']
let arr2 =['61dfd02a1f492f4f4f589f00', '61dfcfb71f492f4f4f589e93', '61dedd23bd15322626dd7539']
you can do something like this
let uniqueArray = Array.from(new Set([...arr1, ...arr2]))
console.log(uniqueArray)
I am having a filtering problem..
objArray is the array that needs to be filtered.
selectedNames is an array that contains the values that I want to find in objArray.
I need to fetch all objects that have one or more values from selectedNames in their "names" property (an array) .
The output I am trying to get is :
let result = [{names:["A","B","C","D"]},
{names:["A","B"]},
{names:["A","D"]}
]
Here is a simplified version of my code:
let objArray = [{names:["A","B","C","D"]},
{names:["C","D"]},
{names:["C","D","E"]},
{names:["A","B"]},
{names:["A","D"]}
]
let selectedNames = ["A","B"]
result = this.objArray .filter(obj => {
return this.selectedNames.includes(obj.names)
}
My code seems to work fine if names attribute was a single value and not an array. But I can't figure out how to make it work on an array.
Any help is more than welcome
You could do something like this. Filtering the array based on the names property having 'some' value be included in the selectedNames array.
...
objArray.filter(obj => obj.names.some(name => selectedNames.includes(name)));
[Edit] As #RadicalTurnip pointed out, this is not performant if the selectedNames is too large. I would suggest that you use an object. E.x
...
const selectedNamesMap = selectedNames.reduce((p,c) => ({...p, [c]: true}), {});
objArray.filter(obj => obj.names.some(name => selelectedNamesMap[name]));
Overkill, but if the arrays are really large (millions of elements) then you are better of using regular for loop and not array methods.
This result is not performant scaled up, but I don't know that there is any way to ensure that it will be performant unless you know more information (like the names are already sorted). That being said, you just missed one more piece of logic.
result = this.objArray.filter(obj => {
let toReturn = false;
obj.names.forEach(name => {
if (this.selectedNames.includes(name))
toReturn = true;
};
};
return toReturn;
};
I got a result like this :
const result = [ 'arg', 'arg2', '[opt1, opt2]' ]
How can I check in this array if a string can be a array ('[opt1, opt2]') and formate it in real array ?
Thank you
EDIT :
I explain all problem :
I want create a script :
yarn start arg1 arg2 "[option1, option2]"
I need a array of options but I can have a lot args without restrictions, when I recover the result :
const res = process.argv.slice(2)
How can I find my array of options ?
You can try the following solution with string manipulation
const result = ['arg', 'arg2', "[option1, option2]"]
const output = result.map(item => {
if (/^\[.+\]$/.test(item)) {
const prepared = item
.replace('[', '["')
.replace(']', '"]')
.replace(/([a-zA-Z0-9]+),+\s+/g, '$1", "')
return JSON.parse(prepared)
}
return item
})
console.log(output)
Explanation:
/^\[.+\]$/ regex - checks whether the element is an array (based on the presence of matching square brackets)
all other replace statements change the string into valid string encoded JSON array.
Since the overall result is a valid string encoded JSON array, just use JSON.parse after that and return it.
I'm working with an object containing multiple network interfaces with the interfaces' names as keys and then interfaces' informations as values :
What I would like to do is a Vue.js computed property to filter this object by Keys and create arrays that contain all GigabitEthernet separately for example so I can iterate over it in my template.
I thinked about using Regex, here is the one that I use and match the interfaces I want to put in a separate array :
const regex = /^(Te|GigabitEthernet|FastEthernet)+\s?([0-9]+\/){0,}[0-9]+$/g;
The problem is that the main object received from API isn't an array so I can't use find() or filter() functions over it...
If anyone as any idea it would be nice, thanks !
EDIT :
After trying Jaromanda's solution :
It returns only 1 line out of 2...
Here is the code :
const regex = /^(Ten|GigabitEthernet|FastEthernet)\d+[/]?[\d+]?[/]?[\d+]?[.]?[\d+]?[/]?[\d+]?[/]?[\d+]?[:]?[\d+]?$/g;
var rslt = {};
Object.fromEntries(
Object.entries(this.cmdResult).filter(([key, value]) => {
if (regex.test(key)) {
rslt[key] = value;
}
})
);
return rslt;
Here is a screenshot of current output at the left and expected output at the right :
EDIT 2 :
Here is what happens when I console log the regex results with the associated key :
As you can see only 1 out of 2 is true...
This is other solution, using map.
const cmdResult = {
"GigabitEthernet1/0/2": {name: ""},
"GigabitEthernet1/0/3": {name: ""},
"GigabitEthernet1/0/4": {name: ""}
}
const regex = /(GigabitEthernet||FastEthernet\d+(\.\d)*)/i;
const rslt = {};
Object.keys(cmdResult)
.filter((key) => regex.test(key))
.map(prop => rslt[prop] = cmdResult[prop])
console.log(rslt);
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);