Angular JS splice items from the Response based on two parameters - javascript

This is my JSON response . I am able to splice out elements from controller side using something like this . Now comes a situation where my employees can have same employee id but different Type . So i would like to remove itesm from the response by comparing both Id & type. For example I need to remove the emplooyee with Id ABC and type D only . How can i splice them out how can i proceed
var searchresponse = [{
"items": [{
"employeeId": "ABC",
"type": "D",
"alive": "Yes"
}, {
"employeeId": "ABC",
"type": "P",
"alive": "Yes"
}, {
"employeeId": "NPK",
"type": "D",
"alive": "Yes"
}, {
"employeeId": "PKN",
"type": "A",
"alive": "Yes"
}],
"more": false
}];
var data1 = ["ABC"];
var data2 = ["D"] //- how to splice ABC also comparing the D
var items = searchresponse[0].items;
for (var i = items.length - 1; i >= 0; i--) {
if (data1.indexOf(items[i].employeeId) != -1) {
items.splice(i, 1);
}
}

If i understand u right.. will it be ok to just extend the if clause?
if (data1.indexOf(items[i].employeeId) != -1 && data2.indexOf(items[i].type) != -1)

Using array.prototype.filter method
var filterd =searchresponse[0].items.filter(function (item) {
return item.employeeId == "ABC"&& item.type== "D"
})
You may Also use underscore.js simple javascript library in your case
var filterd=_.where(searchresponse[0].items, {employeeId: "ABC", type: "D"});
will give you
[{
"employeeId": "ABC",
"type": "D",
"alive": "Yes"
}]
Check this working fiddle

Related

Splice or Remove list of elements from JSON Array ,removing even numbered items only instead of matching items

I am having a JSON Array Output from REST API like this , I am displaying this items on the HTML using ng-repeat.
var searchresponse = [{
"items": [{
"employeeId": "ABC",
"type": "D",
"alive": "Yes"
}, {
"employeeId": "DEF",
"type": "D",
"alive": "Yes"
}, {
"employeeId": "NPK",
"type": "D",
"alive": "Yes"
}, {
"employeeId": "PKN",
"type": "A",
"alive": "Yes"
}],
"more": false
}];
when user tries to delete using selectall/single select i am calling a REST API to remove the employee id from the db . once i get a successful response i am planning to splice / remove the values that have been selected by the user from the VIEW. I would like to remove the following employeeid and their type,alive removed from the searchresponse
var data1=["ABC","NPK","PKN"];
I tried it doing like this
var data1=["ABC","NPK"];
var items=searchresponse[0].items;
for(i in items){
if(data1.indexOf(items[i].employeeId)!=-1){
items.splice(i,1);
}
}
console.log(searchresponse[0].items);
What happens really is, it removed even numbered items only eg :it removed ABC,PKN . (It is removing 0th ,2nd,4th items in the list . Leaving 1st,3rd items etc).What am i missing here
The problem is when you remove the item from array, the index of other items in the array shift to the left.
Assume you have 4 items in the array([a, b, c, d]) and you are removing the first item so i=0 then the resulted array in the second iteration will be [b,c,d] and i will be i=1 now effectively you have missed b in the loop
var searchresponse = [{
"items": [{
"employeeId": "ABC",
"type": "D",
"alive": "Yes"
}, {
"employeeId": "DEF",
"type": "D",
"alive": "Yes"
}, {
"employeeId": "NPK",
"type": "D",
"alive": "Yes"
}, {
"employeeId": "PKN",
"type": "A",
"alive": "Yes"
}],
"more": false
}];
var data1 = ["ABC", "NPK", "PKN"];
var data1 = ["ABC", "NPK"];
var items = searchresponse[0].items;
for (var i = items.length - 1; i >= 0; i--) {
if (data1.indexOf(items[i].employeeId) != -1) {
items.splice(i, 1);
}
}
console.log(searchresponse[0].items);

Delete element with a specific value from an array

I use vue.js and I want to delete elements of an array that have specific id value.
For example :
I want to delete elements that have id of 0. I tried to use the findindex and then delete the element but I couldn't implement that, and to use the splice method you have to know the index before deleting.
"Options": [
{
"id": 0,
"option": "A",
"value": "2"
},
{
"id": 0,
"option": "B",
"value": "1"
},
{
"id": 0,
"option": "C",
"value": "3"
},
{
"id": 1,
"option": "A",
"value": "1"
}
One more (polyfill):
var array = [{id:1},{id:0},{id:0},{id:2}];
array = array.filter(x => x.id != 0);
console.log(array);
x => x.id != 0 is the same as function (x) { return x.id != 0; }.

Getting values from array that matches a regular expression using lodash

My json array:
[{"id":"7","name":"hello"},{"id":"7","name":"shan"},{"id":"7","name":"john"}
{"id":"7","name":"hello"}]
I want to get a new array that matches a regular expression on name starting with a letter.
I am using regexp but i don't know how to implement it.
Here is my code:
var newitem=_.filter(result,item=>item.name='hello');
console.log(newitem);
But it returns with only strict match of name.
Please help me to modify the above so that the result is a new array as described.
Expected output
when a usertype letter h it shows only the row
{"id":"7","name":"hello"}
To check if the name starts with a string, you can use RegExp#test with regex.
var newItem = _.filter(result, obj => /^[a-zA-Z]/.test(obj.name));
The regex ^[a-zA-Z] will check if the name starts with alphabet.
var arr = [{
"id": "7",
"name": "hello"
}, {
"id": "7",
"name": "shan"
}, {
"id": "7",
"name": "jhon"
}, {
"id": "7",
"name": "hello"
}, {
id: 10,
name: '$haun'
}];
var newItem = _.filter(arr, obj => /^[a-zA-Z]/.test(obj.name));
console.log(newItem);
<script src="https://cdnjs.com/libraries/lodash.js/"></script>
Same code can be written using Array#filter.
arr.filter(obj => /^[a-zA-Z]/.test(obj.name));
var arr = [{
"id": "7",
"name": "hello"
}, {
"id": "7",
"name": "*shan"
}, {
"id": "7",
"name": "jhon"
}, {
"id": "7",
"name": "hello"
}, {
id: 10,
name: '$haun'
}];
var newItem = arr.filter(obj => /^[a-zA-Z]/.test(obj.name));
console.log(newItem);
document.body.innerHTML = '<pre>' + JSON.stringify(newItem, 0, 4) + '</pre>';
Update:
when a usertype letter h it shows only the row
You can use
_.filter(result, obj => /^h/.test(obj.name));
Use i-case insensitive flag to match the alphabet irrespective of the case. That'll match both h and H.
regex ('^h.') should work on this. To get row with name h.

sort and pattern match an json

Am having a json like below,
[
{
"id": "1",
"freq": "1",
"value": "Tiruchengode",
"label": "Tiruchengode"
},
{
"id": "2",
"freq": "1",
"value": "Coimbatore",
"label": "Coimbatore"
},
{
"id": "3",
"freq": "1",
"value": "Erode",
"label": "Erode"
},
{
"id": "4",
"freq": "1",
"value": "Madurai",
"label": "Madurai"
},
{
"id": "5",
"freq": "1",
"value": "Salem",
"label": "Salem"
},
{
"id": "6",
"freq": "1",
"value": "Tiruchirappalli",
"label": "Tiruchirappalli"
},
{
"id": "7",
"freq": "1",
"value": "Tirunelveli",
"label": "Tirunelveli"
}
]
I need to pattern match it with label item in this json (ie), If I type tiru, then it has to result label items having tiru substrings in it.If its a single item array I know how to pattern match and sort it. Here am completely unaware that, how to pattern match using label item in the array. Is it possible to?. I need to do with Pure javascript, any help guys?
You can use the functional array methods introduced in JavaScript 1.6, specifically filter:
var search = 'tiru';
var results = obj.filter(function(item) {
var a = item.label.toUpperCase();
var b = search.toUpperCase();
return a.indexOf(b) >= 0;
});
If you wanted labels only, you can then use map to return only that property alone:
var labels = obj.filter(function(item) {
var a = item.label.toUpperCase();
var b = search.toUpperCase();
return a.indexOf(b) >= 0;
}).map(function(item) {
return item.label;
});
Essentially, filter is a method available to any Array which returns a new Array containing only those members for which the supplied function return true.
JSON.parse() will help convert the jsonString to JsonObject then just iterate the object use indexOf for pattern matching.
var jsonString = '[{"id": "1","freq": "1","value": "Tiruchengode","label": "Tiruchengode"},{"id": "2","freq": "1","value": "Coimbatore","label": "Coimbatore"},{"id": "3","freq": "1","value": "Erode","label": "Erode"},{"id": "4","freq": "1","value": "Madurai","label": "Madurai"},{"id": "5","freq": "1","value": "Salem","label": "Salem"},{"id": "6","freq": "1","value": "Tiruchirappalli","label": "Tiruchirappalli"},{"id": "7","freq": "1","value": "Tirunelveli","label": "Tirunelveli"}]';
var jsonObjects = JSON.parse(jsonString);
var pattern = "tiru";
for(var key in jsonObjects){
var label = jsonObjects[key].label.toUpperCase();
if(label.indexOf(pattern.toUpperCase()) != -1){
document.write(label+"<br/>");
}
}

Javascript sort object string with numbers

I have the following JSON object in javascript:
var stuff = [{
"id": "20",
"serial": "0/0/19:46,0/0/149:63"
}, {
"id": "8",
"serial": "0/0/151:215,0/0/151:233"
}, {
"id": "54",
"serial": "0/0/151:26,0/0/151:37"
}, {
"id": "22",
"serial": "0/0/155:29,0/0/155:36"
}, {
"id": "4",
"serial": "0/0/151:48,0/0/151:152"
}];
I would like to know how to sort the object by the "serial" field, leaving it like this (taking into account the value of the integers in the serial string):
var stuff = [{
"id": "20",
"serial": "0/0/19:46,0/0/149:63"
}, {
"id": "54",
"serial": "0/0/151:26,0/0/151:37"
}, {
"id": "4",
"serial": "0/0/151:48,0/0/151:152"
}, {
"id": "8",
"serial": "0/0/151:215,0/0/151:233"
}, {
"id": "22",
"serial": "0/0/155:29,0/0/155:36"
}];
Thanks in advance.
This will do it for you:
var normalizer = /[:\/]/g;
function serialCompare(a, b) {
var alist = a.serial.replace(normalizer, ',').split(','),
blist = b.serial.replace(normalizer, ',').split(','),
i = 0, l = alist.length;
while (alist[i] === blist[i] && i < l) {
i += 1;
};
return (parseInt(alist[i], 10) - parseInt(blist[i], 10));
}
sortedstuff = stuff.sort(serialCompare);
// returns array sorted as you asked
See it in a fiddle.
If you are going to be sorting often, or the list is very long, you should consider creating a "normalized" version of the serial value that gets stored in the object. It could be the array as calculated inside the serialCompare function, or it could be the text number parts padded to the same lengths with leading zeroes.
You have an array of objects, which you want to sort by one of their properties. You could very easily do it like this:
stuff.sort(function(a,b) {return a.serial == b.serial ? 0 : a.serial < b.serial ? -1 : 1;});
Alternatively, you could have a more general function:
function sort(input,prop) {
input.sort(function(a,b) {return a[prop] == b[prop] ? 0 : a[prop] < b[prop] ? -1 : 1;});
}
// call with:
sort(stuff,'serial');

Categories