Comparing one array value with another array - javascript

I have an array with values like :
userID: ["55f6c3639e3cdc00273b57a5",
"55f6c36e9e3cdc00273b57a6", "55f6c34e9e3cdc00273b57a3"];
$scope.userList : [Object, Object, Object, Object, Object],
where each object has an ID property of which i am comparing.
I want to compare whether the each userID array value exist in userList array or not.
$scope.userInfo = function(userID) {
var userDetails = [];
for (var i = 0; i < $scope.userList.length; i++) {
(function(i) {
for (var j = i; j < userID.length; j++) {
if ($scope.userList[i]._id === userID[j]) {
userDetails.push($scope.userList[i]);
}
}
})(i)
}
return userDetails;
};
The problem i am facing is for each userID in the array, i want to compare it with all the items in userList object to match.
The above code is not working. Its not comparing each array values with the entire object.

Instead of using 2 nested loops, convert $scope.userList into an object that has the userID as the key. Then you can loop through your userID array and quickly check if a user with the same key exists in your new object.
By removing the nested loops, the code below runs in linear time instead of n^2, which is beneficial if you have large arrays. And if you store $scope.userList as an object that's keyed by its userId, then you can save even more time by not having to create the index each time the function is run.
$scope.userInfo = function(userID) {
var userList = {};
//create object keyed by user_id
for(var i=0;i<$scope.userList.length;i++) {
userList[$scope.userList._id] = $scope.userList;
}
//now for each item in userID, see if an element exists
//with the same key in userList created above
var userDetails = [];
for(i=0;i<userID.length;i++) {
if(userID[i] in userList) {
userDetails.push(userList[userID[i]]);
}
}
return userDetails;
};

try this
$scope.userInfo = function(userID) {
var userDetails = [];
for (var i = 0; i < $scope.userList.length; i++) {
for (var j = 0; j < userID.length; j++) {
if ($scope.userList[i]._id === userID[j]) {
userDetails.push(userID[j]);
}
}
}
return userDetails;
};
Changes in this lines on if statement
var j = 0;
and
userDetails.push(userID[j]);

You should try using $filter.
JS:
var userIds = ["55f6c3639e3cdc00273b57a5",
"55f6c36e9e3cdc00273b57a6", "55f6c34e9e3cdc00273b57a3"];
$scope.userList = [
{id: "55f6c3639e3cdc00273b57a5", name: "ASD"},
{id: "55f6c36e9e3cdc00273b57a6", name: "XYZ"}
];
$scope.filteredList = $filter('filter')( $scope.userList, function(user){
return userIds.indexOf(user.id) != -1;
});
http://plnkr.co/edit/J6n45yuxw4OTdiQOsi2F?p=preview

Related

How to Splice in a javascript array based on property?

I am getting an array of data in Angularjs Grid and I need to delete all the rows which has same CustCountry
ex - My Customer Array looks like
Customer[0]={ CustId:101 ,CustName:"John",CustCountry:"NewZealand" };
Customer[1]={ CustId:102 ,CustName:"Mike",CustCountry:"Australia" };
Customer[2]={ CustId:103 ,CustName:"Dunk",CustCountry:"NewZealand" };
Customer[3]={ CustId:104 ,CustName:"Alan",CustCountry:"NewZealand" };
So , in the Grid I need to delete all three records if CustomerCountry is NewZealand
I am using splice method and let me know how can I use by splicing through CustomerCountry
$scope.remove=function(CustCountry)
{
$scope.Customer.splice(index,1);
}
If you're okay with getting a copy back, this is a perfect use case for .filter:
Customer = [
{ CustId:101 ,CustName:"John",CustCountry:"NewZealand" },
{ CustId:102 ,CustName:"Mike",CustCountry:"Australia" },
{ CustId:103 ,CustName:"Dunk",CustCountry:"NewZealand" },
{ CustId:104 ,CustName:"Alan",CustCountry:"NewZealand" },
]
console.log(Customer.filter(cust => cust.CustCountry !== "NewZealand"));
if you have one specific country in mind then just use .filter()
$scope.Customer = $scope.Customer.filter(obj => obj.CustCountry !== "SpecificCountry")
If you want to delete all objects with duplicate countries then, referring to Remove duplicate values from JS array, this is what you can do:
var removeDuplicateCountries = function(arr){
var dupStore = {};
for (var x= 0; x < arr.length; x++){
if (arr[x].CustCountry in dupStore){
dupStore[arr[x].CustCountry] = false;
} else {
dupStore[arr[x].CustCountry] = true;
}
}
var newarr = [];
for (var x= 0; x < arr.length; x++){
if (dupStore[arr[x].CustCountry]){
newarr.push(arr[x]);
}
}
return arr;
};
$scope.Customer = removeDuplicateCountries($scope.Customer);
Or incorporating the .filter() method
var removeDuplicateCountries = function(arr){
var dupStore = {};
var newarr = arr;
for (var x= 0; x < arr.length; x++){
if (arr[x].CustCountry in dupStore){
newarr = newarr.filter(obj => obj.CustCountry !== arr[x].CustCountry);
} else {
dupStore[arr[x].CustCountry] = true;
}
}
return newarr;
};
$scope.Customer = removeDuplicateCountries($scope.Customer);
if there are many duplicate countries then use the way without .filter()

Create Dynamic Object Javascript

i just wanted to create a Dynamic Object in JS, but the Object only saves the last Element of the foor loop. Heres my Code :
for(var i = 0; i < req.session.userObjekt.length; i++) {
var userObjekt = {
[req.session.userObjekt[i].User]: {
Data : req.session.userObjekt[i].Data,
Admin: req.session.userObjekt[i].Admin
}
};
}
When i output in the for loop i get the correct result (7 Users + Properties)
When i output out of the for loop, i only get the last User + Properties.
How to save all Elements from the for loop in my Object?
Thanks in advance.
Because you assign to your userObjekt a new object in each iteration. Move out your object declaration from the for loop body
var userObjekt = { };
for(var i = 0; i < req.session.userObjekt.length; i++) {
userObjekt[req.session.userObjekt[i].User] = {
Data : req.session.userObjekt[i].Data,
Admin: req.session.userObjekt[i].Admin
};
}
You can create an array outside of loop and just push the objects in it later on you can use the declared and filled array:
var objektArr = [];
for(var i=0; i<req.session.userObjekt.length; i++) {
var userObjekt = {
[req.session.userObjekt[i].User]: {
Data : req.session.userObjekt[i].Data,
Admin: req.session.userObjekt[i].Admin
},
};
objektArr.push(userObjekt);
}
console.log(objektArr);

How to concatenate values of duplicate keys

When reading a csv into a javascript dictionary, how can I concatenate values of what would otherwise be duplicate keys? I've seen answers for how to do this with bash, c#, and perl, but I haven't been able to find answers for Javascript. Here's what I have:
var subjects = {};
d3.csv("test.csv", function(data) {
for (var i = 0; i < data.length; i++)
{
subjects[data[i].Id] = data[i].VALUE;
}
console.log(subjects);
});
This, obviously writes over existing keys. Instead, I want the key to be an array of the values. The csv basically looks like:
Id, VALUE
id1, subject1
id2, subject1
id1, subject3
And I want to output as:
{"id1": ["subject1", "subject3"], "id2": ["subject1"]...}
Just check if your output already has the key, if so you add the new value to the array. Else you create an array.
d3.csv("test.csv", function(data) {
var subjects = {};
for (var i = 0; i < data.length; i++)
{
// Check if key already exists
if(subjects.hasOwnProperty(data[i].Id)){
// push data to array
subjects[data[i].Id].push(data[i].VALUE);
}else{
// create new key and array
subjects[data[i].Id] = [data[i].VALUE];
}
}
console.log(subjects);
});
You could make it into an array and then push the content into that array
var subjects = {};
d3.csv("test.csv", function(data) {
for (var i = 0; i < data.length; i++)
{
//first time we see this id, turn it into an array
if(typeof subjects[data[i].Id] != "object"){
subjects[data[i].Id] = [];
}
//push content to the array
subjects[data[i].Id].push(data[i].VALUE);
}
console.log(subjects);
});
Try this inside the for loop:
typeof subjects[data[i].Id] == 'undefined' && (subjects[data[i].Id] = []);
subjects[data[i].Id].push(data[i].VALUE);
You can reduce the footprint of your code slightly if you use reduce:
var out = data.reduce((p, c) => {
const id = c.Id;
p[id] = p[id] || [];
p[id].push(c.VALUE);
return p;
}, {});
RESULT
{
"id1": [
"subject1",
"subject3"
],
"id2": [
"subject1"
]
}
DEMO

Remove data from an array comparing it to an other array

I am trying to compare the items in "item" array and the copyofOpList array to retrieve the data occurrences in copyofOpList
this is my try:
var _deleteUsedElement1 = function(item) {
for (var i = 0; i < item.length-1; i++){
for (var j = 0; j< $scope.copyofOpList.length-1; j++){
if (item[i].operationCode == $scope.copyofOpList[j].code) {
$scope.copyofOpList.splice(j, 1);
} } } };
$scope.compareArrays = function() {
...Get data from web Service
_deleteUsedElement1(item);
}
the copyofOpList array has 14 elements,and the item array has 2 array
but my code deletes only one occurrence (the first),so please how can I correct my code,to retrieve any occurances in the copyofOpList array comparing to the item array
thanks for help
I'd try to avoid looping inside a loop - that's neither a very elegant nor a very efficient way to get the result you want.
Here's something more elegant and most likely more efficient:
var item = [1,2], copyofOpList = [1,2,3,4,5,6,7];
var _deleteUsedElement1 = function(item, copyofOpList) {
return copyofOpList.filter(function(listItem) {
return item.indexOf(listItem) === -1;
});
};
copyofOpList = _deleteUsedElement1(item, copyofOpList);
console.log(copyofOpList);
//prints [3,4,5,6,7]
}
And since I just noticed that you're comparing object properties, here's a version that filters on matching object properties:
var item = [{opCode:1},{opCode:2}],
copyofOpList = [{opCode:1},{opCode:2},{opCode:3},{opCode:4},{opCode:5},{opCode:6},{opCode:7}];
var _deleteUsedElement1 = function(item, copyofOpList) {
var iOpCodes = item.map(function (i) {return i.opCode;});
return copyofOpList.filter(function(listItem) {
return iOpCodes.indexOf(listItem.opCode) === -1;
});
};
copyofOpList = _deleteUsedElement1(item, copyofOpList);
console.log(copyofOpList);
//prints [{opCode:3},{opCode:4},{opCode:5},{opCode:6},{opCode:7}]
Another benefit of doing it in this manner is that you avoid modifying your arrays while you're still operating on them, a positive effect that both JonSG and Furhan S. mentioned in their answers.
Splicing will change your array. Use a temporary buffer array for new values like this:
var _deleteUsedElement1 = function(item) {
var _temp = [];
for (var i = 0; i < $scope.copyofOpList.length-1; i++){
for (var j = 0; j< item.length-1; j++){
if ($scope.copyofOpList[i].code != item[j].operationCode) {
_temp.push($scope.copyofOpList[j]);
}
}
}
$scope.copyofOpList = _temp;
};

How can I find which index in an array contains an object whose value for a specific key is x? [duplicate]

I would like to find index in array. Positions in array are objects, and I want to filter on their properties. I know which keys I want to filter and their values. Problem is to get index of array which meets the criteria.
For now I made code to filter data and gives me back object data, but not index of array.
var data = [
{
"text":"one","siteid":"1","chid":"default","userid":"8","time":1374156747
},
{
"text":"two","siteid":"1","chid":"default","userid":"7","time":1374156735
}
];
var filterparams = {userid:'7', chid: 'default'};
function getIndexOfArray(thelist, props){
var pnames = _.keys(props)
return _.find(thelist, function(obj){
return _.all(pnames, function(pname){return obj[pname] == props[pname]})
})};
var check = getIndexOfArray(data, filterparams ); // Want to get '2', not key => val
Using Lo-Dash in place of underscore you can do it pretty easily with _.findIndex().
var index = _.findIndex(array, { userid: '7', chid: 'default' })
here is thefiddle hope it helps you
for(var intIndex=0;intIndex < data.length; intIndex++){
eachobj = data[intIndex];
var flag = true;
for (var k in filterparams) {
if (eachobj.hasOwnProperty(k)) {
if(eachobj[k].toString() != filterparams[k].toString()){
flag = false;
}
}
}
if(flag){
alert(intIndex);
}
}
I'm not sure, but I think that this is what you need:
var data = [{
"text":"one","siteid":"1","chid":"default","userid":"8","time":1374156747
}, {
"text":"two","siteid":"1","chid":"default","userid":"7","time":1374156735
}];
var filterparams = {userid:'7', chid: 'default'};
var index = data.indexOf( _.findWhere( data, filterparams ) );
I don't think you need underscore for that just regular ole js - hope this is what you are looking for
var data = [
{
"text":"one","siteid":"1","chid":"default","userid":"8","time":1374156747
},
{
"text":"two","siteid":"1","chid":"default","userid":"7","time":1374156735
}
];
var userid = "userid"
var filterparams = {userid:'7', chid: 'default'};
var index;
for (i=0; i < data.length; i++) {
for (prop in data[i]) {
if ((prop === userid) && (data[i]['userid'] === filterparams.userid)) {
index = i
}
}
}
alert(index);

Categories

Resources