How to filter array based on id in angularJS - angularjs

i have multiple data for one id , i want filter my data like this
$scope.mpArray =[
{ Id: 1, Name: Madhu, Address: Upal },
{ Id: 1, Name: Chandu, Address: Upal },
{ Id: 2, Name: Srinu, Address: Kphb },
{ Id: 2, Name: Vijay, Address: kphb },
{ Id: 3, Name: Ajay, Address: Banglore },
{ Id: 3, Name: Narsi, Address: Banglore },
{ Id: 3, Name: Peter, Address: Banglore },
];
i want to filter my array like this
var FilterArray = [
{ Id: 1,Madhu, Chandu},
{ Id: 2, Srinu, Vijay},
{ Id: 3, Ajay, Narsi, Peter},
];

At first you need to change your FilterArray to
[
{
"Id": 1,
"Name": [
"Madhu",
"Chandu"
]
},
{
"Id": 2,
"Name": [
"Srinu",
"Vijay"
]
},
{
"Id": 3,
"Name": [
"Ajay",
"Narsi",
"Peter"
]
}
]
Notice that name is an array. The FilterArray of your question
var FilterArray = [
{ Id: 1,Madhu, Chandu},
{ Id: 2, Srinu, Vijay},
{ Id: 3, Ajay, Narsi, Peter},
];
Do not contain a valid JSON object inside the array so you need to change the structure to the one where add a new key Name in the JSON object of FilterArray as like the first structure above. Then the below code works great.
$(document).ready(function(){
var myArray =[
{ Id: 1, Name: "Madhu", Address: "Upal" },
{ Id: 1, Name: "Chandu", Address: "Upal" },
{ Id: 2, Name: "Srinu", Address: "Kphb" },
{ Id: 2, Name: "Vijay", Address: "kphb" },
{ Id: 3, Name: "Ajay", Address: "Banglore" },
{ Id: 3, Name: "Narsi", Address: "Banglore" },
{ Id: 3, Name: "Peter", Address: "Banglore" },
];
var FilterArray = [];
var matched;
for(var i=0;i<myArray.length; i++){
matched = false;
var myArrayId = myArray[i].Id;
for(var j=0; j<FilterArray.length; j++){
var FilterArrayId = FilterArray[j].Id;
if(myArrayId === FilterArrayId){
matched = true;
FilterArray[j].Name.push(myArray[i].Name);
// no need to loop further
break;
}
}
if(!matched){
var obj = {
'Id' : myArrayId,
'Name' : [myArray[i].Name],
}
FilterArray.push(obj);
}
}
console.log(FilterArray);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

try this
var mpArray =[
{ Id: 1, Name: 'Madhu', Address: 'Upal' },
{ Id: 1, Name: 'Chandu', Address: 'Upal' },
{ Id: 2, Name: 'Srinu', Address: 'Kphb' },
{ Id: 2, Name: 'Vijay', Address: 'kphb' },
{ Id: 3, Name: 'Ajay', Address: 'Banglore' },
{ Id: 3, Name: 'Narsi', Address: 'Banglore' },
{ Id: 3, Name: 'Peter', Address: 'Banglore' },
];
var filterObject = {};
mpArray.forEach(function (item) {
if (!filterObject[item.Id]) {
filterObject[item.Id] = [];
}
filterObject[item.Id].push(item.Name);
});
console.log(filterObject);

$scope.mpArray =[
{ Id: 1, Name: 'Madhu', Address: 'Upal' },
{ Id: 1, Name: 'Chandu', Address: 'Upal' },
{ Id: 2, Name: 'Srinu', Address: 'Kphb' },
{ Id: 2, Name: 'Vijay', Address: 'kphb' },
{ Id: 3, Name: 'Ajay', Address: 'Banglore' },
{ Id: 3, Name: 'Narsi', Address: 'Banglore' },
{ Id: 3, Name: 'Peter', Address: 'Banglore' },
];
var FilterArray = [];
var FilteredArrayIds=[];
$scope.mpArray.forEach(
function(detailObj) {
if(FilteredArrayIds.indexOf(detailObj.Id)==-1)
return FilteredArrayIds.push(detailObj.Id);
});
for(var i=0; i<FilteredArrayIds.length;i++)
{
var result = $scope.mpArray.filter(function( obj ) {
return obj.Id == FilteredArrayIds[i];
});
var rsltNames = result.map(function(obj){
return obj.Name;
})
var filteredObj ={
id:FilteredArrayIds[i]+',' +rsltNames.join()
}
FilterArray.push(filteredObj);
}
console.log(filteredObj)

Related

How to manipulate the object inside the array using javascript?

var arr = [
{ id: 1, name: 'Ahmed Malick', school: 'TEWGS' },
{ id: 2, name: 'Tehmeed Anwar', school: 'DGS' },
{ id: 3, name: 'Azhar Yameen', school: 'DGS' }
]
I want this output:
The student name is his id is and he studies in
Can you please show me what kind of output you expect. Then i will try to solve it.
I'm not sure if this is what you want
var arr = [
{ id: 1, name: "Ahmed Malick", school: "TEWGS" },
{ id: 2, name: "Tehmeed Anwar", school: "DGS" },
{ id: 3, name: "Azhar Yameen", school: "DGS" },
];
arr.map((student) => {
return `Name: ${student.name}, id: ${student.id}, he studies in: ${student.school}`;
}).forEach((output) => {
console.log(output);
});
If you want it in the DOM do this
let html = arr.map((student) => {
return `<p><strong>Name</strong>: ${student.name}, <strong>id</strong>: ${student.id},<strong> he studies in</strong> ${student.school}</p>`;
}).join("")
document.createElement("div").innerHTML = html
Try thatGood luck

How to filter multiple objects from a list objects by a property array?

I have a object array in which each object contain an id and a name and a separate array contains a set of ids. I want to filter first array based on the second array.
const data= [
{
id: 1,
name: 'name1'
},
{
id: 2,
name: 'name2'
},
{
id: 3,
name: 'name3'
},
{
id: 4,
name: 'name4'
}
];
const array = [1,3,4];
const expectedResult= [
{
id: 1,
name: 'name1'
},
{
id: 3,
name: 'name3'
},
{
id: 4,
name: 'name4'
}
];
Use .filter and .includes
const data= [
{
id: 1,
name: 'name1'
},
{
id: 2,
name: 'name2'
},
{
id: 3,
name: 'name3'
},
{
id: 4,
name: 'name4'
}
];
const array = [1, 3, 4]
const result = data.filter((item) => {
//gives us items that passes a condition
return array.includes(item.id)
})
console.log(result)

jQuery select array from data attributes

I'm trying to give an array to my makeSlider function.
The HTML5 Data attribute selects the correct array. Unfortunately, it is not interpreted as an array.
It does not work:
 values = $(this).data("slider");
makeSlider(sliderID, targetID, values);
Is working:
makeSlider(sliderID, targetID, dataMehrfachauswahlmatrixLeft);
HTML:
<div class="noui-slider" id="slider-1" data-slider="dataMehrfachauswahlmatrixLeft">
<!-- slider here -->
</div>
<div class="hidden-md-up">
<!-- Store selected value -->
<input class="form-control slider-value" id="input-target-1">
</div>
JS (script.js):
$(document).ready(function() {
// slider array
// Matrix 1
var dataMehrfachauswahlmatrixLeft = [{
id: 1,
value: "sehr wichtig"
}, {
id: 2,
value: ""
}, {
id: 3,
value: ""
}, {
id: 4,
value: ""
}, {
id: 5,
value: "unwichtig"
}, {
id: null,
value: "weiß nicht"
}];
// Matrix 2
var dataMehrfachauswahlmatrixRight = [{
id: 1,
value: "in hohem Maße"
}, {
id: 2,
value: ""
}, {
id: 3,
value: ""
}, {
id: 4,
value: ""
}, {
id: 5,
value: "in geringem Maße"
}, {
id: null,
value: "weiß nicht"
}];
// build slider
var makeSlider = function(sliderID, targetID, values) {
...
}
// init slider
$(".noui-slider").each(function(index) {
var sliderID = $(this).attr("id"),
targetID = $(this).next().find(".slider-value").attr("id");
values = $(this).data("slider");
makeSlider(sliderID, targetID, values);
});
});
Problem with current implementation it that the variable value doesn't refers to the defined array. Its a string literal having value i.e. dataMehrfachauswahlmatrixLeft, dataMehrfachauswahlmatrixRight
Define the array in window or any other object scope.
// Matrix 1
window.dataMehrfachauswahlmatrixLeft = [...];
// Matrix 2
window.dataMehrfachauswahlmatrixRight = [...]
Then use Bracket notation to access object dynamic properties.
values = $(this).data("slider");
makeSlider(sliderID, targetID, window[values]);
An example here
$(document).ready(function() {
var myOBj = {};
// slider array
// Matrix 1
myOBj.dataMehrfachauswahlmatrixLeft = [{
id: 1,
value: "sehr wichtig"
}, {
id: 2,
value: ""
}, {
id: 3,
value: ""
}, {
id: 4,
value: ""
}, {
id: 5,
value: "unwichtig"
}, {
id: null,
value: "weiß nicht"
}];
// Matrix 2
myOBj.dataMehrfachauswahlmatrixRight = [{
id: 1,
value: "in hohem Maße"
}, {
id: 2,
value: ""
}, {
id: 3,
value: ""
}, {
id: 4,
value: ""
}, {
id: 5,
value: "in geringem Maße"
}, {
id: null,
value: "weiß nicht"
}];
// build slider
var makeSlider = function(sliderID, targetID, values) {
console.log(values)
}
$(".noui-slider").on('click', function() {
var values = $(this).data("slider");
makeSlider(1, 2, myOBj[values]);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='noui-slider' data-slider='dataMehrfachauswahlmatrixLeft'>1</div>
<div class='noui-slider' data-slider='dataMehrfachauswahlmatrixRight'>2</div>

Controller As with local function

I'm taking an udemy course on AngularJS- but rewriting all of the example projects using the 'controller as' syntax. This seems to be breaking when I use a local function. In the controller below, this.customers isn't available within the init() function. I've tested this with the strategic placement of console.logs. This seems to work fine if I'm using $scope.
Can anybody help me puzzle this out? The instructor introduced the 'Controller as' syntax but hasn't been using it throughout the course.
(function(){
var OrdersController = function($routeParams) {
var customerId = $routeParams.customerId;
this.orders = null; //not required
this.customers=[
{
id: 1,
joined: '2000-12-02',
name:'John',
city:'Chandler',
orderTotal: 9.9956,
orders: [
{
id: 1,
product: 'Shoes',
total: 9.9956
}
]
},
{
id: 2,
joined: '1965-01-25',
name:'Zed',
city:'Las Vegas',
orderTotal: 19.99,
orders: [
{
id: 2,
product: 'Baseball',
total: 9.995
},
{
id: 3,
product: 'Bat',
total: 9.995
}
]
},
{
id: 3,
joined: '1944-06-15',
name:'Tina',
city:'New York',
orderTotal:44.99,
orders: [
{
id: 4,
product: 'Headphones',
total: 44.99
}
]
},
{
id: 4,
joined: '1995-03-28',
name:'Dave',
city:'Seattle',
orderTotal:101.50,
orders: [
{
id: 5,
product: 'Kindle',
total: 101.50
}
]
}
];
//console.log(this.customers);
init = function () {
//Search the customers for the customerId - local function
console.log(this.customers);
for (var i=0,len=this.customers.length;i<len;i++) {
if (this.customers[i].id === parseInt(customerId)) {
this.orders = this.customers[i].orders;
break;
}
}
}
init();
};
//OrdersController.$inject = ['$routeParams'];
angular.module('customersApp')
.controller('OrdersController', OrdersController);
}());
First assign your this object to a variable:
var vm = this;
Then use the vm variable instead of this:
vm.orders = null; //not required
vm.customers=[
{
id: 1,
joined: '2000-12-02',
name:'John',
city:'Chandler',
orderTotal: 9.9956,
orders: [
{
id: 1,
product: 'Shoes',
total: 9.9956
}
]
},
{
id: 2,
joined: '1965-01-25',
name:'Zed',
city:'Las Vegas',
orderTotal: 19.99,
orders: [
{
id: 2,
product: 'Baseball',
total: 9.995
},
{
id: 3,
product: 'Bat',
total: 9.995
}
]
},
{
id: 3,
joined: '1944-06-15',
name:'Tina',
city:'New York',
orderTotal:44.99,
orders: [
{
id: 4,
product: 'Headphones',
total: 44.99
}
]
},
{
id: 4,
joined: '1995-03-28',
name:'Dave',
city:'Seattle',
orderTotal:101.50,
orders: [
{
id: 5,
product: 'Kindle',
total: 101.50
}
]
}
];
And finally in your function console log the array:
init = function () {
//Search the customers for the customerId - local function
console.log(vm.customers);
for (var i=0,len=vm.customers.length;i<len;i++) {
if (vm.customers[i].id === parseInt(customerId)) {
vm.orders = vm.customers[i].orders;
break;
}
}
}

Protractor promise produces array that overrides previous values [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 7 years ago.
I have angular ui grid that I am trying to get values from its cells. Here is my list in table
id name
1 AUSTRIA
2 BELGIUM
3 BULGARIA
4 CROATIA
5 CZECH REPUBLIC
This is code I run:
element(by.id('grid1')).all(by.repeater('(rowRenderIndex, row) in rowContainer.renderedRows track by $index')).then(function (items) {
for (var i = 0; i < items.length; i++) {
var country = <any>{}; //typescript code
self.gridTestUtils.dataCell('grid1', i, 0).getText().then(
function (valueId) {
country.id = valueId
});
self.gridTestUtils.dataCell('grid1', i, 1).getText().then(
function (valueName) {
country.name = valueName;
self.countryList.push(country)
console.log(self.countryList)
});
}
});
And this is result
[ { id: 1, name: 'AUSTRIA' }]
[ { id: 1, name: 'BELGIUM' },
{ id: 1, name: 'BELGIUM' }]
[ { id: 1, name: 'BULGARIA' },
{ id: 1, name: 'BULGARIA' },
{ id: 1, name: 'BULGARIA' } ]
[ { id: 1, name: 'CROATIA' },
{ id: 1, name: 'CROATIA' },
{ id: 1, name: 'CROATIA' },
{ id: 1, name: 'CROATIA' } ]
[ { id: 1, name: 'CZECH REPUBLIC' },
{ id: 1, name: 'CZECH REPUBLIC' },
{ id: 1, name: 'CZECH REPUBLIC' },
{ id: 1, name: 'CZECH REPUBLIC' },
{ id: 1, name: 'CZECH REPUBLIC' } ]
I expect result would look like:
[ { id: 1, name: 'AUSTRIA' }]
[ { id: 1, name: 'AUSTRIA' },
{ id: 1, name: 'BELGIUM' }]
[ { id: 1, name: 'AUSTRIA' },
{ id: 1, name: 'BELGIUM' },
{ id: 1, name: 'BULGARIA' } ]
[ { id: 1, name: 'AUSTRIA' },
{ id: 1, name: 'BELGIUM' },
{ id: 1, name: 'BULGARIA' },
{ id: 1, name: 'CROATIA' } ]
[ { id: 1, name: 'AUSTRIA' },
{ id: 1, name: 'BELGIUM' },
{ id: 1, name: 'BULGARIA' },
{ id: 1, name: 'CROATIA' },
{ id: 1, name: 'CZECH REPUBLIC' } ]
What is wrong with my code? What should I do that I have expected array
The problem is that i in your loop changes as the loops goes through, and in your async calls you are using i and getting a promise, but it's only a reference, so at the time the promises get resolved, the will have the reference to the variable with the last value of the loop. A workaround is to create an IIFE:
element(by.id('grid1')).all(by.repeater('(rowRenderIndex, row) in rowContainer.renderedRows track by $index')).then(function (items) {
for (var i = 0; i < items.length; i++) {
var country = <any>{}; //typescript code
(function (i, country) {
self.gridTestUtils.dataCell('grid1', i, 0).getText().then(function (valueId) {
country.id = valueId;
});
self.gridTestUtils.dataCell('grid1', i, 1).getText().then(function (valueName) {
country.name = valueName;
self.countryList.push(country)
console.log(self.countryList)
});
})(i, country);
}
});

Resources