I am trying below code but its not working so first am trying to get a person department Name currently, hard coded it to check
var arr=[]
let CurrDept = "AB-CDE-F";
var Detept=CurrDept.substring(0,5);
arr.push(Detept)
Now in below line of code i am trying this line so it should exclude all results which start from AB-CD
var Userprofiledept=data.value[0].UserId.Department;
const isInArray = arr.indexOf(Userprofiledept) > -1;
isInArray should be false which can be put in my condition but it always give true
Can anyone help ?
So current user department may be AB-CDE-F and data i am getting from my rest call may have lots of department for many users AB-CDE-F,AB-CDE-F,AB-CDE,AB-CD,AB-C
so only want to exclude results which are AB-CDE-F,AB-CDE-F,AB-CDE,AB-CD as they are starting with AB-CD
You can use Array.prototype.filter and String.prototype.startsWith.
const
data = {value: [{ UserId: { ID: 14, Email: "sdfds", Department: "AB-CD-EF" } }, { UserId: { ID: 14, Email: "sdfds", Department: "AB-CD" } }, { UserId: { ID: 14, Email: "sdfds", Department: "AB-C" } }]},
discard = "AB-CD",
res = data.value.filter((v) => !v.UserId.Department.startsWith(discard));
console.log(res);
You could move the functionality into a function and check if the substring exists and add, if necessary.
const
add = string => {
string = string.slice(0, 5);
if (array.includes(string)) return;
array.push(string);
}
array = [];
add('AB-CDE-F');
console.log(array);
add('AB-CDE-F');
console.log(array);
add('AB-CDE');
console.log(array);
Related
I have an array which contains some java script objects and I am using ejs for display data but the problem is - that I have to filter that data in the bases of req.params.id and want to next 2 data objects..! after filtering data -- please help
my code is -
app.get("/:id", (req, res) => {
const requestParams = _.lowerCase(req.params.id);
let obj = blogData.find((o) => o.heading >= "Yoga-During-COVID");
console.log(obj);
blogData.forEach(function (post) {
const storedTitel = _.lowerCase(post.heading);
if (storedTitel === requestParams) {
res.render("blogfullDetail", {
date: post.date,
heading: post.heading,
subheading: post.subheading,
discription: post.discription,
discription2: post.discription2,
author: post.author,
authorImage: post.authorImage,
mainImg: post.mainImg,
});
}
});
});
data file -
Use a combination of findIndex and slice. findIndex returns the index of the matching element and slice returns a sub-array from that index to a computed higher index...
let blogData = [{
id: 1,
title: 'yoga is good'
},
{
id: 32,
title: 'yoga helps you stretch'
},
{
id: 12,
title: 'covid yoga is good too'
},
{
id: 41,
title: 'no such thing as too much yoga'
},
{
id: 57,
title: 'is hot yoga too hot'
}
];
// say you need the post about covid...
let targetTitle = 'covid yoga is good too';
let index = blogData.findIndex(p => p.title === targetTitle);
// with the index, answer a slice of the blogs
// starting at that index, ending 3 later
let posts = blogData.slice(index, index + 3);
console.log(posts)
I have the following object:
[ { id:
'/subscriptions/resourcegroups/coco-test/providers/microsoft.devtestlab/schedules/shutdown-computevm-runscripts2',
name: 'shutdown-computevm-runscripts2' },
{ id:
'/subscriptions/resourcegroups/coco-test/providers/microsoft.devtestlab/schedules/shutdown-computevm-packer',
name: 'shutdown-computevm-packer' } ]
I am trying to write a script that does something if it can't find a specific value in the name key of any of this object.
Example: shutdown-computevm-test
If there is no name anywhere in this object that matches this value, then I want my code to do something.
I'm new to nodejs, I tried things like includes(), indexOf etc, but these are either not the correct ways to do it or I never got the syntax right.
Any hints are appreciated.
Something like this should work for you;
const result = [ { id:
'/subscriptions/resourcegroups/coco-test/providers/microsoft.devtestlab/schedules/shutdown-computevm-runscripts2',
name: 'shutdown-computevm-runscripts2' },
{ id:
'/subscriptions/resourcegroups/coco-test/providers/microsoft.devtestlab/schedules/shutdown-computevm-packer',
name: 'shutdown-computevm-packer' } ];
const found = result.some((part) => part.name === 'shutdown-computevm-test');
if (! found) {
// do something here
}
I prefer it to filter as it won't wait to iterate over all items in the array and will shortcut as soon as it is found.
Use Array.prototype.find()
const arr = [ { id:
'/subscriptions/resourcegroups/coco-test/providers/microsoft.devtestlab/schedules/shutdown-computevm-runscripts2',
name: 'shutdown-computevm-runscripts2' },
{ id:
'/subscriptions/resourcegroups/coco-test/providers/microsoft.devtestlab/schedules/shutdown-computevm-packer',
name: 'shutdown-computevm-packer' } ]
let rs = arr.find(item => item.name === 'shutdown-computevm')
let rs2 = arr.find(item => item.name === 'shutdown-computevm-runscripts2')
console.log(rs) // undefined
console.log(rs2) // obj
Trying to wrap my brain around how I should tackle filtering an array of objects and only returning results that satisfy all of the tags.
The tags could be any of the fields - fname/lname/email/position/etc
let search_tags = ['CEO', 'Steven'];
let contacts = [
{ fname: 'Steve', lname: 'Johnson', email: 'user#domain.com', position: 'CEO' },
{ fname: 'James', lname: 'Laurence', email: 'boss#domain.com', position: 'CFO' }
]
let results = contacts.filter((contact) => {
if (search_tags.includes(contact.fname) ||
search_tags.includes(contact.lname) ... ) {
return contact;
}
}
I shortened a bit of the code for brevity and obviously this solution will return contacts that match any search_tag but... I need to only return results that satisfy every search_tag.
It's been a long day and I have no one to talk this through so I'm hoping someone may be able to point me in the right direction or give me that ah-ha! moment I'm hoping for :)
Thanks in advance!
If you wanted to return one that matched every search tag you'd want to use && instead of || but that still leaves you with a bunch of verbose and duplicated code
Instead of operating directly on the contact Object, you can use Object.values() https://mdn.io/objectvalues which would give you an array of ['steve', 'johnson', 'user#domain]... etc.
Then you could in your filter:
contacts.filter((contact) => {
const contactValues = Object.values(contact);
// Return the search item if at least one item matches
// Would return true if at least one item matches
return contactValues.some(value => search_tags.includes(value));
// return true only if all search tags match
return contactValues.every(value => search_tags.includes(value));
}
Object.values is quite a new feature, so if you don't have it available in babel, then you can use Object.keys and grab the value using contact[someKey]
Array.prototype.filter() can be combined with Array.prototype.every(), Object.values() and Array.prototype.includes() to construct an Array of matches consisting solely of contact Objects that contain a matching value for every element in search_tags.
See below for a practical example.
// Search Tags.
const search_tags = ['CEO', 'Steven']
// Contacts.
let contacts = [
{ fname: 'Steven', lname: 'Johnson', email: 'user#domain.com', position: 'CEO' },
{ fname: 'James', lname: 'Laurence', email: 'boss#domain.com', position: 'CFO' }
]
// Matches.
const matches = contacts.filter((contact) => search_tags.every((tag) => Object.values(contact).includes(tag)))
// Log.
console.log(matches)
ES6:
function filterIt(arr, searchKeys) {
return arr.filter(obj => Object.keys(obj).some(key => searchKeys.includes(obj[key])));
}
I have two arrays:
myFriends = [ 0: { uid: 123abc }, 1: { uid:456def }, ];
theirFriends = [ 0: { uid: 123abc }, 1: { uid:789ghi }];
Now I want to see if the theirFriends array has an object with the same uid as as an object in the myFriends array and if it does, then set theirFriends[object].isFriend = true; if it doesn't, then set it to false instead.
so it should run through and ultimately set theirFriends[0].isFriend = true. and theirFriends[1].isFriend = false
So the new theirFriends array should be:
theirFriends = [ 0: { uid: 123abc, isFriend: true }, 1: { uid: 789ghi, isFriend: false }];
I have tried: .some(), .map(), .filter(), .forEach(), but I have yet to find a solution that works, but doesn't continously run everytime the object is updated with the new value.
First, you can convert your friend's list to a Set. Sets contain only unique values and it's fast to check if a value is included. Then, you can map over theirFriends and add the new property.
const myFriendSet = new Set(myFriends.map( friend => friend.uid ))
theirFriends = theirFriends.map( friend => ({
uid: friend.uid,
isFriend: myFriendSet.has(friend.uid)
})
hi this is what i came up with
var myF = [ { uid: "123abc" }, { uid: "456def" } ];
var theirF = [ { uid: "123abc" }, { uid: "789ghi" }]
//loop through all their friends
for(var i = 0; i < theirF.length; i++)
{
//loop through all my friends for comparison
for(var j = 0; j < myF.length; j++)
{
if(!theirF[i].isFriend) //if isFriend is not set
theirF[i].isFriend = theirF[i].uid == myF[j].uid; //set current theirFriend isFriend propery
}
}
Lodash _.isEqual is great for comparing objects.
Here is the oneliner using forEach and some:
theirFriends.forEach(tf => tf.isFriend = myFriends.some(mf => mf.uid === tf.uid));
Example:
myFriends = [{uid: '123abc'}, {uid:'456def'}, {uid: '789abc'}, {uid:'789def'}];
theirFriends = [{uid: '123abc'}, {uid:'789ghi'}, {uid: '789def'}, {uid:'000ert'}];
theirFriends.forEach(tf => tf.isFriend = myFriends.some(mf => mf.uid === tf.uid));
console.log(theirFriends);
What is the best way to filter out data that exists within an object?
I was able to do use the below code when data was just an array of values but now I need to filter out any data where the item.QID exists in my array of objects.
Data Obj:
var data = [{
QID: 'ABC123',
Name: 'Joe'
},
{
QID: 'DEF456',
Name: 'Bob
}]
Snippet:
// I don't want to include data if this QID is in my object
this.employees = emp.filter(item =>!this.data.includes(item.QID));
From what I understand, includes only works on an array so I need to treat all of the QID values in my object as an array.
Desired Outcome: (assuming item.QID = ABC123)
this.employees = emp.filter(item =>!this.data.includes('ABC123'));
Result:
var data = [{
QID: 'DEF456',
Name: 'Bob'
}]
UPDATE:
Apologies, I left some things a little unclear trying to only include the necessary stuff.
// People Search
this.peopleSearchSub = this.typeahead
.distinctUntilChanged()
.debounceTime(200)
.switchMap(term => this._mapsService.loadEmployees(term))
.subscribe(emp => {
// Exclude all of the current owners
this.employees = emp.filter((item) => item.QID !== this.data.QID);
}, (err) => {
this.employees = [];
});
The above code is what I am working with. data is an object of users I want to exclude from my type-ahead results by filtering them out.
The question is a little ambiguous, but my understanding (correct me if I'm wrong), is that you want to remove all items from a list emp that have the same QID as any item in another list data?
If that's the case, try:
this.employees = emp.filter(item => !this.data.some(d => d.QID === item.QID))
some is an array method that returns true if it's callback is true for any of the arrays elements. So in this case, some(d => d.QID === item.QID) would be true if ANY of the elements of the list data have the same QID as item.
Try Object#hasOwnProperty()
this.employees = emp.filter(item =>item.hasOwnProperty('QID'));
You can use a for ... in to loop through and filter out what you want:
const data = [{
QID: 'ABC123',
Name: 'Joe'
},
{
QID: 'DEF456',
Name: 'Bob'
}]
let newData = [];
let filterValue = 'ABC123';
for (let value in data) {
if (data[value].QID !== filterValue) {
newData.push(data[value]);
}
}
newData will be your new filtered array in this case
You can use an es6 .filter for that. I also added a couple of elements showing the filtered list and an input to allow changing of the filtered value. This list will update on the click of the button.
const data = [{
QID: 'ABC123',
Name: 'Joe'
},
{
QID: 'DEF456',
Name: 'Bob'
}]
displayData(data);
function displayData(arr) {
let str = '';
document.getElementById('filterList').innerHTML = '';
arr.forEach((i) => { str += "<li>" + i.QID + ": " + i.Name + "</li>"})
document.getElementById('filterList').innerHTML = str;
}
function filterData() {
let filterValue = document.getElementById('filterInput').value;
filterText (filterValue);
}
function filterText (filterValue) {
let newArr = data.filter((n) => n.QID !== filterValue);
displayData(newArr)
}
<input id="filterInput" type="text" value="ABC123" />
<button type ="button" onclick="filterData()">Filter</button>
<hr/>
<ul id="filterList"><ul>