How to filter array object from another array object? - arrays

I want to make another array object from an array object, suppose I fetched a huge data from an api but I need only particular elements from that object. Exampl:-
const mainArray = [
{id: 1, name: 'John', age: 10},
{id: 2, name: 'Mark', age: 14},
{id: 3, name: 'Kevin', age: 15},
{id: 4, name: 'Julie', age: 16},
{id: 5, name: 'Liz', age: 10},
{id: 5, name: 'Emma', age: 11},
{id: 6, name: 'Robert', age: 13},
]
So suppose we have a huge list now I only want Kevin, Emma & Mark to display, for that I need an array of them like this:-
const specialKids = [
{id: 2, name: 'Mark', age: 14},
{id: 3, name: 'Kevin', age: 15},
{id: 5, name: 'Emma', age: 11},
]
How can I achieve that ?

To do this you can use the filter method of JS.
Documentation:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter?retiredLocale=de
in your case something like this should be enough:
let specialKids[];
specialKids = mainArray.filter(item => item.name === "Mark" || item.name === "Kevin" || item.name === "Emma")

ArrayList<String> yourintList = new ArrayList<>(Arrays.asList(yourArray));
for (int i = 0; i < yourintList.lenght; i++) {
if (yourintList.contains("Kevin")) {
do something
}

Related

How to Iterate dictionary in React Typescript

I am learning react with typescript. I have one dictionary of the department in which employees data of department is stored in the form of an array.
type Department = {
Emp_Id: number,
Name: string,
Age: number
}
let dict: {[DepartmentNo: number]: Department[] } = {};
dict[0] = [ {Emp_Id: 1, Name:"Test", Age: 23},
{Emp_Id: 2, Name:"Test", Age: 23},
{Emp_Id: 3, Name:"Test", Age: 23}
];
dict[1] = [ {Emp_Id: 1, Name:"Test 2", Age: 23},
{Emp_Id: 2, Name:"Test 3", Age: 23},
{Emp_Id: 3, Name:"Test 4", Age: 23}
];
dict[2] = [ {Emp_Id: 1, Name:"Test 2", Age: 23},
{Emp_Id: 2, Name:"Test 3", Age: 23}
];
I created a function that will return me an unordered list.
const printDepartment = () => {
// getting error in map argument: department
Object.entries(dict).map((department: Department) => {
let count = 0;
// here also saying condition will always return true
if(dict[count] != 2){
return (<ul>
<li>{department.Emp_Id}</li>
<li>{department.Name}</li>
</ul>)
}
})
}
in my return I am simply calling this function:
<div>
{
printDepartment()
}
</div>
The type of keys on your dict will always be string. If you change that, the types in the Array.map element will be correctly inferred as [string, Department[]].
type Department = {
Emp_Id: number;
Name: string;
Age: number;
};
let dict: { [DepartmentNo: string]: Department[] } = {};
dict[0] = [
{ Emp_Id: 1, Name: "Test", Age: 23 },
{ Emp_Id: 2, Name: "Test", Age: 23 },
{ Emp_Id: 3, Name: "Test", Age: 23 },
];
dict[1] = [
{ Emp_Id: 1, Name: "Test 2", Age: 23 },
{ Emp_Id: 2, Name: "Test 3", Age: 23 },
{ Emp_Id: 3, Name: "Test 4", Age: 23 },
];
dict[2] = [
{ Emp_Id: 1, Name: "Test 2", Age: 23 },
{ Emp_Id: 2, Name: "Test 3", Age: 23 },
];
const printDepartment = () => {
Object.entries(dict).map((entry) => { // [string, Department[]]
console.log({ key: entry[0], value: entry[1] });
});
};
printDepartment();
demo

$route.reload not updating service data

I am very much new to AngularJS.
Generally I have seen people using $route for refreshing data from database. But for learning purpose I have created an object in the custom service, stored some data in the Object and calling that service in the controller.
But when I am adding more values in the object and try to update it using the ngClick, no changes take place. Though, on refreshing the whole page, changes takes place. But I just want that particular section to update.
Here's my JavaScript code:
var app=angular
.module('app',['ngRoute'])
.service('data', function(){
this.students=[
{id: 1, name: 'Mark', gender: 'Male', city: 'London'},
{id: 2, name: 'Henry', gender: 'Male', city: 'Manchester'},
{id: 3, name: 'John', gender: 'Male', city: 'Chennai'},
{id: 4, name: 'Sara', gender: 'Female', city: 'Sydney'},
{id: 5, name: 'Tom', gender: 'Male', city: 'New York'},
{id: 6, name: 'Pam', gender: 'Male', city: 'Los Angeles'},
{id: 7, name: 'Catherine', gender: 'Female', city: 'Chicago'},
{id: 8, name: 'Mary', gender: 'Female', city: 'Houston'},
{id: 9, name: 'Mike', gender: 'Male', city: 'Phoenix'},
{id: 10, name: 'Rosie', gender: 'Female', city: 'Manchester'},
{id: 11, name: 'Sasha', gender: 'Female', city: 'Hyderabad'},
{id: 12, name: 'Naatasha', gender: 'Female', city: 'Bhungi'},
// {id: 13, name: 'akash', gender: 'Male', city: 'lugi'},
// {id: 14, name: 'aaakash', gender: 'Male', city: 'lugi'}
];
})
.controller('studentcontroller',function($scope,data,$route){
$scope.rdata=function(){
console.log("asd");
$route.reload();
};
$scope.students=data.students;
});
Here's the code calling it
<h1>List of Students</h1>
<ul>
<li ng-repeat="student in students">
{{student.name}}
</li>
</ul>
<button ng-click="rdata()">Reload Data</button>
Please help me in learning something new.

Angular show list in alphabetical order and also show divider

**please anyone can help me i want to print list in Angularjs like this **
enter image description here
Use Order by
$scope.friends = [
{name: 'John', phone: '555-1212', age: 10},
{name: 'Mary', phone: '555-9876', age: 19},
{name: 'Mike', phone: '555-4321', age: 21},
{name: 'Adam', phone: '555-5678', age: 35},
{name: 'Julie', phone: '555-8765', age: 29}
];
<tr ng-repeat="friend in friends | orderBy:'name'">
read more here
You have to filter each group by the letters you want. Here's a Plunker Using this list:
$scope.myList = [{
id: 11,
name: 'Okra'
}, {
id: 12,
name: 'Musa'
}, {
id: 4,
name: 'Sky'
}, {
id: 13,
name: 'India'
}, {
id: 14,
name: 'Rose'
}, {
id: 15,
name: 'Titanic'
}, {
id: 16,
name: 'Onion'
}, {
id: 6,
name: 'Germany'
}, {
id: 17,
name: 'Beer'
}, {
id: 18,
name: 'Run'
}, {
id: 2,
name: 'Garden'
}, {
id: 19,
name: 'Mountain'
}]
One function to get the alphabets between the two:
function genCharArray(charA, charZ) {
var a = [], i = charA.charCodeAt(0), j = charZ.charCodeAt(0);
for (; i <= j; ++i) {
a.push(String.fromCharCode(i));
}
return a;
};
Then your filter:
app.filter("cfilter", function () {
return function (input, x, y) {
var groups = [];
var letters = genCharArray(x, y);
for (var i = 0; i < input.length; i++) {
for (var x = 0; x < letters.length; x++) {
if (input[i].name.substring(0, 1) == letters[x])
groups.push(input[i]);
}
} return groups;
}
});
And your HTML:
<div ng-repeat="w in myList | cfilter: 'A':'H' | orderBy: 'name'">
<div>{{w.name}}</div>
</div>
create one directive pass an array of letter and range of alphabates you want to disaply.
<dummy-directive data="arrayData" range="A-G"></dummy-directive>
<dummy-directive data="arrayData" range="H-L></dummy-directive>
<dummy-directive data="arrayData" range="M-P"></dummy-directive>
<dummy-directive data="arrayData" range="Q-Z"></dummy-directive>
Now question is that how to implement directive?
we will display sorted data.

Merge two arrays of objects in Ruby

I have an array of objects with unique IDs:
[{id: 1, score: 33}, {id: 23, score: 50}, {id:512, score: 27}, ...]
I also have an array of User records with matching IDs. The user records have "name" but not "score":
[{id: 1, name: "Jon"}, {id: 23, name: "Tom"}, {id: 512, name: "Joey"}, ...]
How can I create a single array with each id, name, and score?
[{id: 1, name: "Jon", score: 33}, {id: 23, name: "Tom", score: 50}, {id: 512, name: "Joey", score: 27}, ...]
I tried merge, combine, filter, etc but haven't found the Ruby function to accomplish this.
Assuming that in users there is always record with corresponding :id from scores:
scores = [{id: 1, score: 33}, {id: 23, score: 50}, {id:512, score: 27}]
users = [{id: 1, name: "Jon"}, {id: 23, name: "Tom"}, {id: 512, name: "Joey"}]
scores = scores.map { |score| score.merge(users.find { |user| user[:id] == score[:id] }) }
# => [{:id=>1, :score=>33, :name=>"Jon"}, {:id=>23, :score=>50, :name=>"Tom"}, {:id=>512, :score=>27, :name=>"Joey"}]
Hope that puts you in proper direction!
You can use an intermediate Hash.
hsh = Hash[ a1.map {|h| [h[:id], h[:score]]} ]
# => {1=>33, 23=>50, 512=>27}
a2.map {|h| h[:score] = hsh[h[:id]]; h}
# => [{:id=>1, :name=>"Jon", :score=>33}, {:id=>23, :name=>"Tom", :score=>50}, {:id=>512, :name=>"Joey", :score=>27}]
If, as in the example, scores[i][:id] = users[i][:id] for all i, and you are using v1.9+ (where key insertion order is maintained), you could write:
scores.zip(users).each_with_object({}) do |(sh,uh),h|
h.update(sh).update(uh)
end
Would I use this? Would you?

KendoUI Grid - filter not showing

In my angular-kendo application I'm unable to get the Grid filter to show at all - not even a filter icon, just plain column headers.
Here is my html:
<div ng-controller="IntroductionWizardCtrl">
<h3 class="text-muted">Step 2: Select Application To Describe</h3>
<div kendo-grid id="grid"
k-data-source="dataSource"
k-sortable="true"
k-on-change="selectedItem = data"
k-selectable="'row'"
k-pageable='{ "refresh": true, "pageSizes": 5 }'
k-filterable="true">
</div>
<div>
<p>{{selectedItem}}</p>
</div>
<br/>
<input type="submit" class="btn btn-primary" wz-next value="Proceed to Next Step"
data-ng-click="" />
</div>
here is the corresponding Angular controller:
'use strict';
angular.module('wizardApp').controller('IntroductionWizardCtrl', ['$scope', '$location', '$rootScope',
function ($scope, $location, $rootScope) {
$scope.dataSource = {
data: [{id: 1, name: "Account Underwriting - Misc App", bu: 50},
{id: 2, name: "Achieve - Distributed", bu: 43},
{id: 3, name: "ACT!", bu: 27},
{id: 4, name: "Actuarial Database", bu: 29},
{id: 5, name: "Adjustment Invoicing System (AIS)", bu: 34},
{id: 6, name: "buncy Download", bu: 43},
{id: 7, name: "Ariba", bu: 27},
{id: 8, name: "Athena NY", bu: 29},
{id: 9, name: "Authoria", bu: 34},
{id: 10, name: "Avenue", bu: 43},
{id: 11, name: "BC&IT - Services", bu: 27},
{id: 12, name: "Billing Website", bu: 29},
{id: 13, name: "Blue Butler", bu: 34},
{id: 14, name: "BOE External", bu: 43},
{id: 15, name: "Builders Risk", bu: 27},
{id: 16, name: "Business Intelligence", bu: 29},
{id: 17, name: "Care Center", bu: 34}],
pageSize: 5, serverFiltering: true
};
$scope.rowSelected = function(e) {
var grid = e.sender;
var selectedRows = grid.select();
for (var i = 0; i < selectedRows.length; i++) {
$scope.selectedItem = grid.dataItem(selectedRows[i]);
break;
}
};
$scope.categoryDataSelectedRows=[];
$scope.categoryData=
{
data:
[{name: "General Application Information"},
{name: "User Interface configuration description"},
{name: "Application Architecture"},
{name: "Database"},
{ name: "Backup & DR"},
{name: "Design"},
{ name: "Operational data"},
{ name: "Testing"},
{name: "Application Configuration details"},
{ name: "Application connectivity requirements"},
{name: "Deployment Requirements"},
{name: "Application dependencies"},
{name: "Infrastructure dependencies"},
{ name: "Business value assessment"},
{ name: "Data requirements"},
{name: "Hosting OS requirements"},
{ name: "License requirements"}], pageSize: 5
}
$scope.rowSelectedCategory = function(e) {
var gridCategory = e.sender;
var selectedRowsCategory = gridCategory.select();
for (var i = 0; i < selectedRowsCategory.length; i++) {
$scope.selectedItemCategory = gridCategory.dataItem(selectedRowsCategory[i]);
break;
}
};
}
]);
I have looked over many examples, outside of Angular, where Kendo Grid has filtering working just fine. Yet, with angular-kendo I'm having this problem.
Well, as it turns out, my issue was with the order in which various css files were being loaded.
bootstrap was overwriting some other styles. Took me a while to sort this out, but now my angular-kendo grid is OK. Thanks for helping me!

Resources