How To Remove object from Javascript Object Array By Value? [duplicate] - javascript

This question already has answers here:
Remove Object from Array using JavaScript
(32 answers)
Closed 3 years ago.
I am having array of objects defined in javascript and would like to delete values based on object property.
I used below code :
var addedItems = [];
var item = {};
item["TId"] = "";
item["VNo"] = "";
item["IDate"] = "";
item["Rate"] = 22;
item["ItemId"] = 12;
item["Quantity"] = 1;
item["ItemTypeId"] = 3;
addedItems.push(item);
removeValueFromObjectByValue(addedItems,12);
function removeValueFromObjectByValue(jsonObject, value) {
jQuery.each(jsonObject, function (i, val) {
if (val.ItemId == value) // delete index
{
return;
delete jsonObject[i];
return;
}
});
}
Expected Result :
When I remove value, it should give me array with 0 elements.
Actual output :
When I remove value, I am getting array with 1 element and the element value is null.

You can use Object.values and splice. Inside the function create a new copy of the original array using JSON.parse & JSON.stringify so that original array does not get modified. Inside the forEach callback use Object.values which will give an array of values. Then use includes to check if this array created using Object.values contains the parameter passed in the function. If true then remove the element from the copied array using splice
var addedItems = [];
var item = {};
item["TId"] = "";
item["VNo"] = "";
item["IDate"] = "";
item["Rate"] = 22;
item["ItemId"] = 12;
item["Quantity"] = 1;
item["ItemTypeId"] = 3;
addedItems.push(item);
function removeValueFromObjectByValue(arr, num) {
let newArr = JSON.parse(JSON.stringify(arr))
arr.forEach(function(item, index) {
let isNumPresent = Object.values(item).includes(num)
if (isNumPresent) {
newArr.splice(index, 1);
}
})
return newArr;
}
console.log(removeValueFromObjectByValue(addedItems, 12));

Related

Find the index of a sub array that contains a number

var array = [[2,3,4],[4,5,6],[2,3,9]];
var number = 9;
If I have this nested array and this variable how do I return the index
where the sub-array with the number is. So the final result should be 2 or.
So far I have:
var indexOfRemainingArray = array.filter(function(item,i) {
if(item != number) {
return i;
}
});
I would like to know how to use map or filter functions for this.
Use Array#findIndex to find the index, and use Array#indexOf in the callback to check if the sub array contains the number at least once.
var array = [[2,3,4],[4,5,6],[2,3,9]];
var number = 9;
var indexOfRemainingArray = array.findIndex(function(sub) {
return sub.indexOf(number) !== -1;
});
console.log(indexOfRemainingArray);
And if you need both indexes, you can assign the result of the inner indexOf to a variable:
var array = [[2,3,4],[4,5,9],[2,3,1]];
var number = 9;
var innerIndex;
var indexOfRemainingArray = array.findIndex(function(sub) {
innerIndex = sub.indexOf(number);
return innerIndex !== -1;
});
console.log(indexOfRemainingArray, innerIndex);

Looping through array and get the same value only once [duplicate]

This question already has answers here:
How to get unique values in an array [duplicate]
(20 answers)
Closed 6 years ago.
I have an array
var myArray = ['1','1','2','2','1','3'] // 6 item
Is there any ways I can return the value of 1 and 2 and 3 ONE time when looping?
//example in pseudocode
var getNumber = [];
var count = 0;
var check = 0;
for(var i in myArray)
{
if(getNumber[check] !== myArray[i])
{
getNumber[count] = myArray[i];
count++;
}
else
{
}
}
and advice to follow up my previous code?
thanks
You should use Array.indexOf and Array.push to check and insert values.
var getNumber = [];
for(var i in myArray)
{
if(getNumber.indexOf(myArray[i]) < 0) //See if the number wasn't found already
{
getNumber.push(myArray[i]);
}
else
{
//This number was found before. Do nothing!
}
}
you could do something like :
function leaveDupes(arry){
var newArry = [], keys={};
for(var i in arry){
if(!keys[arry[i]]){
newArry.push(arry[i]);
keys[arry[i]]=true;
}
}
return newArry;
}
console.log(leaveDupes(['1','1','2','2','1','3'] ))
using underscore.js, you can do something like:
newArry = _.uniq(['1','1','2','2','1','3']);
var obj = {};
for (var i = 0; i < myArray.length; i++) {
if (!obj[myArray[i]]) {
obj[myArray[i]] = true;
console.log(myArray[i]); //these are the unique values
}
}
This will work.
var myArray = ['1','1','2','2','1','3']
var getNumber = {};
var retArray = [];
myArray.forEach(function(val){
if(!getNumber[val]){
getNumber[val] = val;
retArray.push(val);
}
});
return retArray
You can use forEach and indexOf array method to find the unique elements.
var myArray = ['1','1','2','2','1','3','4','4','5'];
var uniqueArray =[]; //A new array which will hold unique values
function _unique(myArray){
myArray.forEach(function(item,index){
if(uniqueArray.indexOf(item) ==-1){ //Check if new array contains item
uniqueArray.push(item)
}
})
}
_unique(myArray);

Prevent 2 Way Binding of a Variable [duplicate]

This question already has answers here:
What is the most efficient way to deep clone an object in JavaScript?
(67 answers)
Closed 7 years ago.
Below is my code:
var laData = [{fname:"India"}, {fname: "Germany"}];
function modifyData(iaData) {
for (var i = 0; i < iaData.length; i += 1) {
var loNode = {};
loNode = iaData[i];
loNode.states= [];
}
}
modifyData(laData);
In the Output I can see that [{"fname":"India","states":[]},{"fname":"Germany","states":[]}] the states node is getting appended to the Original Array laData.
Question: How do I prevent "States" node to be appended to the laData?
Solution using Jquery.
var laData = [{fname:"India"}, {fname: "Germany"}];
function modifyData(iaData) {
var modifiedData = [];
for (var i = 0; i < iaData.length; i += 1) {
var loNode = {};
loNode = $.extend(true, {}, iaData[i]); //Doing a Deep copy of the object
loNode.states= [];
modifiedData.push(loNode);
}
return modifiedData;
}
var modifiedData = modifyData(laData);
console.log("Original Data:");
console.log(laData);
console.log("Modified Data");
console.log(modifiedData);
Check your browser console to see the different outputs.
You can see that the output of the initial object does not have states appended to it. and Here is the working JSFiddle
You just have to remove one line:
var laData = [{fname:"India"}, {fname: "Germany"}];
function modifyData(iaData) {
for (var i = 0; i < iaData.length; i += 1) {
var loNode = {};
loNode = iaData[i];
//loNode.states= []; <-- remove this line
}
}
modifyData(laData);
The commented line is the one adding an empty array to your node.
If you remove it, you will get the structure you wants

filtering an array for a duplicate value

I have an array of objects, shown below. The first segment of code is within a loop where multiple objects of 'Item' are created and pushed onto the array.
Example of the problem is available here: http://jsfiddle.net/X6VML/
Notice how changing the value inside a textbox displays a duplicate item.
// class
var Item = function(label, value) {
this.Label = label;
this.Value = value;
};
var obj = new Item("My Label", "My Value");
// adds object onto array
itemArray.push(obj);
The problem I have is that the array can contain duplicate objects which I need to filter out before rending the list of objects into a table, shown below:
for (var i = 0; i < itemArray.length; i++) {
$('.MyTable').append("<tr><td>" + itemArray[i].Label + "</td><td>" + itemArray[i].Value + "</td></tr>");
}
I can identify whether it's a duplicate with the Value being the same. How can I filter the list of objects based on whether the Value already exists in the array?
Many thanks
Just don't add duplicate item in array:
var item = new Item("My Label", "My Value1");
if(!$.grep(itemArray, function(obj) { return obj.Value == item.Value; }).length)
itemArray.push(item);
If there is already an object with Value "My Value1" in itemArray, just don't add it.
A simple solution would be:
var temp = [];
$.each(itemArray, function(index, obj){
var found = false;
$.each(temp, function(tempI, tempObj){
if(tempObj.Value == obj.Value){
found = true;
return false;
}
});
if(!found){
temp.push(obj);
}
});
itemArray = temp;
console.log(itemArray);
The above is simply iterating over each object in the array, and pushing it to the temp array if it's not already there, finally it overwrites itemArray with temp.
Have you considered eliminating duplicates at the point of adding to the array? Something like this:
function UniqueItemList(){
var items = [];
this.push = function(item){
for(var i=0; i<items.length; i++){
if(items[i].Value == item.Value){
return;
}
}
items.push(item);
};
this.getList = function(){
return items;
}
}
var myList = new UniqueItemList();
myList.push(new Item('label1', 'value1'));
myList.push(new Item('label2', 'value2'));
myList.push(new Item('label1', 'value1'));
myList.push(new Item('label1', 'value1'));
console.log(myList.getList());
If you try to push a duplicate item, it will be rejected.
Demo - here it is integrated into your code.
This code would do. Modify the itemArray before forming the HTML.
var arr = {};
for ( var i=0; i < itemArray.length; i++ )
arr[itemArray[i].Value] = itemArray[i];
itemArray = new Array();
for ( key in arr )
itemArray.push(arr[key]);
I've got this handy utility function:
function uniq(ary, key) {
var seen = {};
return ary.filter(function(elem) {
var k = (key || String)(elem);
return seen[k] === 1 ? 0 : (seen[k] = 1);
})
}
where key is a function that fetches the comparison key from an element.
Applied to your use case:
uniqueItems = uniq(itemArray, function(item) { return item.Value })

Get a slice of a Javascript Associative Array? [duplicate]

This question already has answers here:
How to get a subset of a javascript object's properties
(36 answers)
Closed 6 years ago.
I have an associative array object in Javascript that I need only part of. With a regular array, I would just use slice to get the part I need, but obviously this won't work on an associative array. Is there any built in Javascript functions that I could use to return only part of this object? If not, what would be considered best practices for doing so? Thanks!
There's not going to be a good way to 'slice' the Object, no, but you could do this if you really had to:
var myFields = ['field1', 'field2', 'field3'];
var mySlice = {};
for (var i in myFields) {
var field = myFields[i];
mySlice[field] = myOriginal[field];
}
There is small function I use:
/**
* Slices the object. Note that returns a new spliced object,
* e.g. do not modifies original object. Also note that that sliced elements
* are sorted alphabetically by object property name.
*/
function slice(obj, start, end) {
var sliced = {};
var i = 0;
for (var k in obj) {
if (i >= start && i < end)
sliced[k] = obj[k];
i++;
}
return sliced;
}
I've created this gist that does exactly this. It returns a new object with only the arguments provided, and leaves the old object intact.
if(!Object.prototype.slice){
Object.prototype.slice = function(){
var returnObj = {};
for(var i = 0, j = arguments.length; i < j; i++){
if(this.hasOwnProperty(arguments[i])){
returnObj[arguments[i]] = this[arguments[i]];
}
}
return returnObj;
}
}
Usage:
var obj = { foo: 1, bar: 2 };
obj.slice('foo'); // => { foo: 1 }
obj.slice('bar'); // => { bar: 2 }
obj; // => { foo: 1, bar: 2 }

Categories

Resources