Remove object from array object Jquery - javascript

I am creating array object like follows:
var numberOfSameDeficiency = [];
for (var i = 0; i < result.length; i++) {
var deficiencyId = result[i].Deficiency_Id;
var deficiencyName = result[i].DeficiencyName;
//check to see if this deficiency is already in the list of available selections
if ($("#drpDeficiency option[value='" + deficiencyId + "']").length == 0) {
var option = $('<option>');
option.attr('value', deficiencyId);
option.text(deficiencyName);
$select.append(option);
}
else {
Tests = {};
Tests.TestId = testId;
Tests.DeficiencyId = deficiencyId;
numberOfSameDeficiency.push(Tests);
}
}
And I want to remove object on different function like this:
for (var i = 0; i < result.length; i++) {
console.log(numberOfSameDeficiency);
var isFound = false;
var deficiencyId = result[i].Deficiency_Id;
if (numberOfSameDeficiency) {
numberOfSameDeficiency.forEach(function (entry) {
if (entry.DeficiencyId != deficiencyId) {
isFound = true;
**numberOfSameDeficiency.splice(entry, 1); // Generating Error (Remove all items from array object)**
return;
}
});
// console.log("end if");
}
if (!isFound) {
$("#drpDeficiency option[value='" + deficiencyId + "']").remove();
}
}
So what line code should be there to remove particular object from array object.

Try this
for( i=myArray.length-1; i>=0; i--) {
if( myArray[i].field == "money") myArray.splice(i,1);
}
This also works
myArray = [{name:"Alpesh", lines:"2,5,10"},
{name:"Krunal", lines:"1,19,26,96"},
{name:"Deep",lines:"3,9,62,36" }]
johnRemovedArray = myArray
.filter(function (el) {
return el.name !== "Krunal";
});

Create this prototype function:
Array.prototype.removeElement = function (el) {
for(let i in this){
if(this.hasOwnProperty(i))
if(this[i] === el)
this.splice(i, 1);
}
}
Then call:
let myArray = ['a','b','c','d'];
myArray.removeElement("c");
It also works with objects:
let myObj1 = {name: "Mike"},
myObj2 = {name: "Jenny"},
myArray = [myObj1, myObj2];
myArray.removeElement(myObj2);

Related

Create Array of Objects and count number of occurrence

I have an array of objects and want to create another array of objects based on.
I want to check if an object is repeated just want to show the count, otherwise show the object itself with count = 1.
<!-- I have an array-->
var arr =[{name:"coke",price:20},{name:"coke",price:20},{name:"coke",price:20},{name:"kabab",price:250}];
// I want to create another array based on "arr" like the one below
var test =[{name:"coke",price:20,count:3},{name:"kabab",price:20,count:1}];
//Any hint please
This may help you. This answer considers name or some identifier will be unique for each object.
counter = {}
var arr = [{
name: "coke",
price: 20
}, {
name: "coke",
price: 20
}, {
name: "coke",
price: 20
}, {
name: "kabab",
price: 250
}];
var obj = {};
var counter = {}
for (var i = 0, len = arr.length; i < len; i++) {
obj[arr[i]['name']] = arr[i];
counter[arr[i]['name']] = (counter[arr[i]['name']] || 0) + 1
}
newArr = new Array();
for (var key in obj){
newArr.push(extend( obj[key], {count:counter[key]}));
}
function extend(a, b){
for(var key in b)
if(b.hasOwnProperty(key))
a[key] = b[key];
return a;
}
console.log(newArr)
var arr =[{name:"coke",price:20},{name:"coke",price:20},{name:"coke",price:20},{name:"kabab",price:250}];
var countNameMapping = {}, finalArr = [];
var arrLength = arr.length;
for(i=0; i<arrLength; i++){
var tempObj = {name:arr[i], price:arr[i].price, occurance:1};
var productName = arr[i].name;
if(countNameMapping[productName] === undefined){
countNameMapping[productName] = tempObj;
}else{
countNameMapping[productName].occurance += 1;
}
}
for(var k in countNameMapping){
finalArr.push(countNameMapping[k])
}
console.log(finalArr );
You can try this one:
var arr =[{name:"coke",price:20},{name:"coke",price:20},{name:"coke",price:20},{name:"kabab",price:250}];
var result = [];
arr.map(function(arrObject) {
if (result.length > 0) {
result.map(function(resultObject) {
if (resultObject.name != arrObject.name) {
arrObject.count = 1;
result.push(arrObject);
} else {
resultObject.count++;
}
})
} else {
arrObject.count = 1;
result.push(arrObject);
}
})
console.log(result);
This will provide the result you are looking for:
var arr =[{name:"coke",price:20},{name:"coke",price:20},{name:"coke",price:20},{name:"kabab",price:250}];
var map = arr.reduce((accum, item) => {
var obj = accum.get(item.name) || Object.assign({}, item, {count:0});
obj.count++;
return accum.set(item.name, obj);
}, new Map());
var res = [...map.values()];
More or less...
var arr = [{
name: "coke",
price: 20
}, {
name: "coke",
price: 20
}, {
name: "coke",
price: 20
}, {
name: "kabab",
price: 250
}];
// I want to create another array based on "arr" like the one below
// var test =[{name:"coke",price:20,count:3},{name:"kabab",price:20,count:1}];
var count = {};
var test = [];
for (var i = 0, len = arr.length; i < len; i++) {
var id = JSON.stringify(arr[i]);
if (count.hasOwnProperty(id)) {
count[id].count++;
} else {
test.push(arr[i]); // Data contamination. Too lazy to copy object
count[id] = test[test.length - 1]; // Could be better.
count[id].count = 1;
}
}
console.log(test);
This is probably what are you looking for:
How does it work?
First, your array arr will use a forEach loop to find each object and if if new you will add it to the results array. The method isNew() will return true if the object is new.
For each new object founded you will count the number of occurrences using findOccurrences() To reduce the number of "loops" you will slice the array according to the index. So you don't need to search again over the already processed data.
So now you can build an new object, using the name, price and count.
Finally, you can push() the new object to the results array.
var arr =[{name:"coke",price:20},{price:20,name:"coke"},{name:"coke",price:20},{name:"kabab",price:250}];
var results = [];
var index = 0;
var originalDiv = document.getElementById('original');
var resultsDiv = document.getElementById('results');
arr.forEach(function(obj) {
if (isNew(obj)) {
var counter = findOccurrences(obj, arr.slice(index, arr.length));
var newObj = {
name: obj.name,
price: obj.price,
count: counter
}
results.push(newObj);
}
index++;
});
printArray(arr, originalDiv);
printArray(results, resultsDiv);
function isNew(newObj) {
var wasFound = true;
if (typeof results != "undefined" && results != null && results.length > 0) {
results.forEach(function(obj) {
if (newObj.name === obj.name && newObj.price === obj.price) {
return false;
} else {
wasFound = false;
}
});
return !wasFound;
} else {
return true;
}
}
function findOccurrences(newObj, objects) {
var count = 0;
if (typeof objects != "undefined" && objects != null && objects.length > 0) {
objects.forEach(function(obj) {
if (newObj.name === obj.name && newObj.price === obj.price) {
count++;
}
});
}
return count;
}
function printArray(objects, div) {
var count = 0;
if (typeof objects != "undefined" && objects != null && objects.length > 0) {
objects.forEach(function(obj) {
var newElement = document.createElement('p');
newElement.innerHTML = 'item ' + count + ': ';
Object.keys(obj).forEach(function(key) {
newElement.innerHTML += key + ': ' + obj[key] + ', ';
});
newElement.innerHTML = newElement.innerHTML.slice(0, -2);
div.appendChild(newElement);
count++;
});
}
}
<div id="original"><p>Original Array</p></div>
<div id="results"><p>Results Array</p></div>
Update:
More optimization.
var arr =[{name:"coke",price:20},{name:"coke",price:20},{name:"coke",price:20},{name:"kabab",price:250},{name:"coke",price:20},{name:"coke",price:20},{name:"kabab",price:250}];
var accumulator = {};
var results = [];
var index = 0;
var originalDiv = document.getElementById('original');
var resultsDiv = document.getElementById('results');
String.prototype.hashCode = function() {
var hash = 0;
if (this.length == 0) return hash;
for (i = 0; i < this.length; i++) {
var char = this.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash |= 0; // Convert to 32bit integer
}
var c = (hash & 0x0FFFFFFF)
.toString(16)
.toUpperCase();
return '0000000'.substring(0, 7 - c.length) + c;
};
arr.forEach(function(obj) {
var id = JSON.stringify(obj).hashCode();
console.log(id);
if (accumulator.hasOwnProperty(id)) {
accumulator[id].count++;
} else {
results.push(obj);
accumulator[id] = results[results.length - 1];
accumulator[id].count = 1;
}
});
printArray(arr, originalDiv);
printArray(results, resultsDiv);
function printArray(objects, div) {
var count = 0;
if (typeof objects != "undefined" && objects != null && objects.length > 0) {
objects.forEach(function(obj) {
var newElement = document.createElement('p');
newElement.innerHTML = 'item ' + count + ': ';
Object.keys(obj).forEach(function(key) {
newElement.innerHTML += key + ': ' + obj[key] + ', ';
});
newElement.innerHTML = newElement.innerHTML.slice(0, -2);
div.appendChild(newElement);
count++;
});
}
}
<div id="original">
<p>Original Array</p>
</div>
<div id="results">
<p>Results Array</p>
</div>

Javascript - Remove duplicates value in array

But I want to leave last two duplicated value in array just like
arr = [1,2,3,4,4,4,4,4,5,6,6,6]
and the result will be
result = [1,2,3,4,4,5,6,6]
The reason why I want to leave last two is I have 2 arrays like date and data and it must match with each other.
Thank you.
Using jquery you can use:
var newarr=[];
$.each(arr, function(i, e) {
if ($.inArray(e, newarr) == -1) newarr.push(e);
});
console.log(newarr)
Try this:
var arr = [1,2,3,4,4,4,4,4,5,6,6,6],
result = [],
fisrtOccurence = -1;
for(var i=0; i<arr.length; i++) {
fisrtOccurence = result.indexOf(arr[i]);
if(fisrtOccurence === -1) {
result.push(arr[i]);
} else {
if(result.indexOf(arr[i],fisrtOccurence+1) === -1) {
result.push(arr[i]);
}
}
}
console.log(result);
Try this solution : JSFiddle
var arr = [1,2,3,4,4,4,4,4,5,6,6,6]
// using reduce function of array
Array.prototype.unique = function() {
return this.reduce(function(previousValue, current) {
if (previousValue.indexOf(current) < 0) {
previousValue.push(current);
}
return previousValue;
}, []);
}
console.log(arr.unique());
// using filter
var filteredArray= arr.filter(function(element, index, self) {
return index == self.indexOf(element);
});
console.log(filteredArray);
Demo
Try this
newarr = [];
testarr = [];
duplicatearr = [];
locArray = [1,2,3,4,4,4,4,4,5,6,6,6];
for (var i = 0; i<locArray.length;i++)
{
var idx = $.inArray(locArray[i], testarr);
if (idx == -1) {
testarr.push(locArray[i]);
newarr.push(locArray[i]);
}
else
{
var id = $.inArray(locArray[i], duplicatearr);
if (id == -1) {
newarr.push(locArray[i]);
duplicatearr.push(locArray[i]);
}
}
}
console.log(newarr);

how to reindex object start from 0

I have an object output from below code how to set the index start from 0 in js?
Object
3: Object
id: 34
type: 0
var obj = {};
var edited = false;
for (var i = 0; i < $(".list").length; i++) {
var data_id = parseInt($(".list").eq(i).attr('data-id'));
var data_type = parseInt($(".list").eq(i).attr('data-type'));
if ((data_type != 0)) {
edited = true;
} else {
edited = false;
}
if (edited == true) {
obj[i] = {};
obj[i]['id'] = data_id;
obj[i]['type'] = data_type;
}
}
console.log(obj);
Needs more jQuery ?
var arr = $(".list").filter(function() {
return $(this).data('type') != 0;
}).map(function() {
return { id : $(this).data('id'), type : $(this).data('type') };
}).get();
FIDDLE
Actually if you want to start in 0, use another variable and not "i" (which I think is 3 when you use it as index).
var obj = {};
var edited = false;
var obj_idx = 0;
for (var i = 0; i < $(".list").length; i++) {
var data_id = parseInt($(".list").eq(i).attr('data-id'));
var data_type = parseInt($(".list").eq(i).attr('data-type'));
if ((data_type != 0)) {
edited = true;
} else {
edited = false;
}
if (edited == true) {
obj[obj_idx] = {};
obj[obj_idx]['id'] = data_id;
obj[obj_idx]['type'] = data_type;
obj_idx += 1;
}
}
console.log(obj);
I think this time obj will be something like:
Object
0: Object
id: 34
type: 0
you could fake object as array by Array.prototype.push.call, in that way you could also gain the side effect: obj.length. it's kinda ninja and elegant :]
var obj = {};
var edited = false;
for (var i = 0; i < $(".list").length; i++) {
var data_id = parseInt($(".list").eq(i).attr('data-id'));
var data_type = parseInt($(".list").eq(i).attr('data-type'));
if ((data_type != 0)) {
edited = true;
} else {
edited = false;
}
if (edited == true) {
Array.prototype.push.call(obj, {id: data_id, type: data_type});
}
}
I am going to give a very simple and readable example. Say you've got an object with the following structure:
Object
0: Object
key: 'some-key'
value: 'some-value'
1: Object
...
Then you might want to delete an entry from it and reindex the whole thing, this is how I do it:
// obj is Object from above
const reIndexed = Object.entries(obj).map((element, index) => {
if (parseInt(element[0] != index) {
element[0] = index.toString();
}
return element;
});

How to filter elements in array in JavaScript object

If I have a JavaScript object like this:
{"products":
[
{
"id":"6066157707315577",
"reference_prefix":"BB",
"name":"BeanieBaby",
"product_line":false,
"has_ideas":true
},
{
"id":"6066197229601550",
"reference_prefix":"BBAGS",
"name":"BlackBags",
"product_line":false,
"has_ideas":false
}
],
"pagination": {
"total_records":4,
"total_pages":1,
"current_page":1
}
}
How do I write a function in js to loop over each pair and only return the elements of the array where has_ideas === true?
I have started with this but I'm stuck. Clearly I am new to this. Any help appreciated.
product: function(mybundle) {
var json = JSON.parse(mybundle.response.content);
for(var i = 0; i < json.length; i++) {
var obj = json[i];
if (json[i].id === "has_ideas" && json[i].value === true) {
return json;
}
return [];
}
}
You can filter out each pair by simply checking that property:
var json = {"products":[{"id":"6066157707315577","reference_prefix":"BB","name":"BeanieBaby","product_line":false,"has_ideas":true},{"id":"6066197229601550","reference_prefix":"BBAGS","name":"BlackBags","product_line":false,"has_ideas":false}],"pagination":{"total_records":4,"total_pages":1,"current_page":1}}
var stuff = json.products.filter(function(obj) {
return obj.has_ideas === true
});
console.log(stuff);
Demo:http://jsfiddle.net/bsyk18cb/
try this
product: function(mybundle) {
var json = JSON.parse(mybundle.response.content);
for(var i = 0; i < json.length; i++) {
if(json[i].has_ideas === true){
return json;
}
return [];
}
}
You want to check the "has_ideas" attribute and if true, return the id.
product: function(mybundle) {
var json = JSON.parse(mybundle.response.content);
for(var i = 0; i < json.length; i++) {
if (json[i].has_ideas === true) {
return json[i].id;
}
return [];
}
}
Use code below.
this will return array of elements having has_ideas=true
var json = "{'products':"+
"["+
"{"+
"'id':'6066157707315577',"+
"'reference_prefix':'BB',"+
"'name':'BeanieBaby',"+
"'product_line':false,"+
"'has_ideas':true"+
"},"+
"{"+
"'id':'6066197229601550',"+
"'reference_prefix':'BBAGS',"+
"'name':'BlackBags',"+
"'product_line':false,"+
"'has_ideas':false"+
"}"+
"],"+
"'pagination': {"+
"'total_records':4,"+
"'total_pages':1,"+
"'current_page':1"+
"}"+
"}";
function filter(){
var jsonArr = [];
var gList = eval( "(" + json + ")");
alert(gList.products.length);
for(var i=0;i<gList.products.length;i++){
if(gList.products[i].has_ideas){
jsonArr.push(gList.products[i]);
}
}
return jsonArr;
}
Demo

Dynamically building array, appending values

i have a bunch of options in this select, each with values like:
context|cow
context|test
thing|1
thing|5
thing|27
context|beans
while looping through the options, I want to build an array that checks to see if keys exist, and if they don't they make the key then append the value. then the next loop through, if the key exists, add the next value, comma separated.
the ideal output would be:
arr['context'] = 'cow,test,beans';
arr['thing'] = '1,5,27';
here's what i have so far, but this isn't a good strategy to build the values..
function sift(select) {
vals = [];
$.each(select.options, function() {
var valArr = this.value.split('|');
var key = valArr[0];
var val = valArr[1];
if (typeof vals[key] === 'undefined') {
vals[key] = [];
}
vals[key].push(val);
});
console.log(vals);
}
Existing code works by changing
vals=[];
To
vals={};
http://jsfiddle.net/BrxuM/
function sift(select) {
var vals = {};//notice I made an object, not an array, this is to create an associative array
$.each(select.options, function() {
var valArr = this.value.split('|');
if (typeof vals[valArr[0]] === 'undefined') {
vals[valArr[0]] = '';
} else {
vals[valArr[0]] += ',';
}
vals[valArr[0]] += valArr[1];
});
}
Here is a demo: http://jsfiddle.net/jasper/xtfm2/1/
How about an extensible, reusable, encapsulated solution:
function MyOptions()
{
var _optionNames = [];
var _optionValues = [];
function _add(name, value)
{
var nameIndex = _optionNames.indexOf(name);
if (nameIndex < 0)
{
_optionNames.push(name);
var newValues = [];
newValues.push(value);
_optionValues.push(newValues);
}
else
{
var values = _optionValues[nameIndex];
values.push(value);
_optionValues[nameIndex] = values;
}
};
function _values(name)
{
var nameIndex = _optionNames.indexOf(name);
if (nameIndex < 0)
{
return [];
}
else
{
return _optionValues[nameIndex];
}
};
var public =
{
add: _add,
values: _values
};
return public;
}
usage:
var myOptions = MyOptions();
myOptions.add("context", "cow");
myOptions.add("context","test");
myOptions.add("thing","1");
myOptions.add("thing","5");
myOptions.add("thing","27");
myOptions.add("context","beans");
console.log(myOptions.values("context").join(","));
console.log(myOptions.values("thing").join(","));
working example: http://jsfiddle.net/Zjamy/
I guess this works, but if someone could optimize it, I'd love to see.
function updateSiftUrl(select) { var
vals = {};
$.each(select.options, function() {
var valArr = this.value.split('|');
var key = valArr[0];
var val = valArr[1];
if (typeof vals[key] === 'undefined') {
vals[key] = val;
return;
}
vals[key] = vals[key] +','+ val;
});
console.log(vals);
}
Would something like this work for you?
$("select#yourselect").change(function(){
var optionArray =
$(":selected", $(this)).map(function(){
return $(this).val();
}).get().join(", ");
});
If you've selected 3 options, optionArray should contain something like option1, option2, option3.
Well, you don't want vals[key] to be an array - you want it to be a string. so try doing
if (typeof vals[key] === 'undefined') {
vals[key] = ';
}
vals[key] = vals[key] + ',' + val;

Categories

Resources