deleting a object of an Array based on property of the object - javascript

I have an Array like this: var obj = [{x:4, y:5}, {x:6, y:2}, ...] and I'm trying to delete one of the inside objects (properties) based on the x.
this is How I'm trying to do this:
obj.forEach(function (child){
if(child.x === 4){
obj.destroy(child)
}
});
But it's not working and i get
obj.destroy is not a funtion
I also tried obj.splice(child) but it just mess up the array. so what am doing wrong here?
Also is there a better way to do this by not having to loop through all of Array property every time?

You can just use filter on the array: e.g.
let arrayToFilter = [ {x:4, y:5}, {x:6, y:2}];
const valueToFilter = 4;
var filteredArray = arrayToFilter .filter((o) => {
return o.x !== valueToFilter;
});
console.log(filteredArray);

forEach() works on array.
If obj is an array, you can simply use filter() to remove the unwanted object from the array:
var obj = [{x:4, y:5}, {x:6, y:2}]
obj = obj.filter(c => c.x !== 4)
console.log(obj);

You perhaps, have an array as obj because the one you posted in the question is simply invalid syntax.
Moreover, you can use Array#findIndex to get the index of the matching element first, and then splice that index from the array.
var obj = [{x:4, y:5}, {x:6, y:2}];
var index = obj.findIndex(item => item.x === 4);
obj.splice(index, 1);
console.log(obj);

i'm assuming your trying to filter out objects in an array which have an x that matches a given value. If thats the case, you should probably use the filter method.
So assuming thats what you mean you could do the following
obj = obj.filter(function (child){
if(child.x !== 4){
return obj
}
});
// shorter
obj = obj.filter( child => child.x !== 4 );
In this case, only the objects which do not have the value of 4 will be available to you in the obj variable. And all other objects (assuming there are no other references in your code) will be garbage collected.

Related

Push unique objects into array in JAVASCRIPT

I want to push object that only have unique id1 into array.
Example:
let array = [],
obj = {},
access = true
if(access){
obj['id1'] = 1
obj['id2'] = 2
if(array.indexOf(obj.id1) == -1){
array.push(obj)
}
}
console.log(array);
In the above example I am trying to add value to obj then push the obj into array. But obj.id1 need to be unique. The method I am using above doesn't work in my case.
Thank you
As Taplar says, indexOf will look for the first instance of the thing you pass in in the other array. This won't work because there are no instances of the ids in the array, directly anyway.
Use the find function, which allow you pass in a comparison function, so you can define what a match is.
let initial = [{id:1}, {id:2}, {id:1}];
let result = initial.reduce((acc, item) =>
{
if(!acc.find(other => item.id == other.id))
{
acc.push(item);
}
return acc;
}, []);
console.log(result);
Simplest solution . Lets say myObjArray have duplicate object use below es6 code to get unique array from that
// Creates an array of objects with unique "name" property values.
let uniqueObjArray = [
...new Map(myObjArray.map((item) => [item["name"], item])).values(), ]; console.log("uniqueObjArray", uniqueObjArray);
Refer here for more detail https://yagisanatode.com/2021/07/03/get-a-unique-list-of-objects-in-an-array-of-object-in-javascript/
I think you need to use findIndex and not indexOf.
Try replacing your if condition with the following:
array.findIndex((o)=>{ return o.id1 === obj.id1 }) === -1

JavaScript - Filter <key,value> Object by key

I am looking for a short and efficient way to filter objects by key, I have this kind of data-structure:
{"Key1":[obj1,obj2,obj3], "Key2":[obj4,obj5,obj6]}
Now I want to filter by keys, for example by "Key1":
{"Key1":[obj1,obj2,obj3]}
var object = {"Key1":[1,2,3], "Key2":[4,5,6]};
var key1 = object["Key1"];
console.log(key1);
you can use the .filter js function for filter values inside an object
var keys = {"Key1":[obj1,obj2,obj3], "Key2":[obj4,obj5,obj6]};
var objectToFind;
var keyToSearch = keys.filter(function(objects) {
return objects === objectToFind
});
The keyToSearch is an array with all the objects filter by the objectToFind variable.
Remember, in the line return objects === objectToFind is where you have to should your statement. I hope it can help you.
You can create a new object based on some custom filter criteria by using a combination of Object.keys and the array .reduce method. Note this only works in es6:
var myObject = {"Key1":["a","b","c"], "Key2":["e","f","g"]}
function filterObjectByKey(obj, filterFunc) {
return Object.keys(obj).reduce((newObj, key) => {
if (filterFunc(key)) {
newObj[key] = obj[key];
}
return newObj;
}, {});
}
const filteredObj = filterObjectByKey(myObject, x => x === "Key1")
console.log(filteredObj)
Not sure what exactly are you trying to achieve, but if you want to have a set of keys that you would like to get the data for, you have quite a few options, one is:
var keys = ['alpha', 'bravo'];
var objectToFilterOn = {
alpha: 'a',
bravo: 'b',
charlie: 'c'
};
keys.forEach(function(key) {
console.log(objectToFilterOn[key]);
});

How to compare each object in an array with each other. When found update the object with a new property

For example consider the following array with objects.
var collection = [{name:'user1',phone:'203'},
{name:'user2',phone:'5050'},
{name:'user1',phone:'203'}]
Now I want to compare the each object with each other and give the result as.
var newCollection = {name:'user1',phone:'203', rowMatch:'true'},
{name:'user2',phone:'5050', rowMatch:'false'},
{name:'user1',phone:'203',rowMatch:'true'}
So, I want the new collecition like this where it compares and updates with new property when object properties match like the first and third object.
var newCollection = collection.map(item => {
item.rowMatch = !!collection.find(i => i !== item && i.phone === item.phone && i.name === item.name);
return item;
});
Here you're just using map to iterate through and check if each item has a duplicate that isn't the original.
You can use newCollection or manipulate in the collection like this
collection.forEach((item)=>{
item.rowMatch = (collection.filter((e)=>{return (e.name==item.name&&e.phone==item.phone)}).length>1)?'true':'false';
})
console.log(collection)
Simple is that.Here is working JSFiddle for it https://jsfiddle.net/touqeer/pgdsw9Le/1/ .
Create a hash function for your object type.
A simple concatenation of the fields seems to work in this case. Iterate through your collection and for each element, hash it, and put it in a table.
Keep track of the counts. When the count is greater than 1 you know you have a duplicate (row match)
JavaScript Hashmap Equivalent
use Array.prototype.find
var newCollection = collection.map((row, index) => {
if(row["rowMatch"])
return row;
rowMatch = !!collection.find((r,i) => i !== index && r.name === row.name && r.phone === row.phone);
row["rowMatch"] = rowMatch;
return row;
})

How to dynamically change the key names of object properties in an array

I have an array of objects, like so:
arr = [{"timeslot":"6am7am","AVG(Monday)":10,"AVG(Tuesday)":11,"AVG(Wednesday)":7}]
Each object will always contain the "timeslot" property, and can contain any combination of the day-of-the-week properties, Monday through Sunday. Each day of the week may only be represented once in a single object.
I want to alter each object: specifically, the key names of the day-of-the-week properties only (the "timeslot" property will be unchanged"), to get an array like so:
newArr = [{"timeslot":"6am7am","Monday":10,"Tuesday":11,"Wednesday":7}]
My slightly unreadable solution works:
// Iterate the array of objects
results.forEach(function(o) {
// Iterate the object's properties
Object.keys(o).forEach(function(k) {
if(k.includes("AVG")) {
var len = k.length;
var pos = len - 1;
var newKey = k.slice(4, pos); // Extract the day of the week from the key name
o[newKey] = o[k]; // Create the new property with the same value and the new key-name
delete o[k]; // Delete the original property
}
});
});
How can I improve this solution?
Instead of mutating the original array by adding and removing keys from each object, Array#map the array into a new array, and recreate the objects using Array#reduce:
var arr = [{"timeslot":"6am7am","AVG(Monday)":10,"AVG(Tuesday)":11,"AVG(Wednesday)":7}];
var result = arr.map(function(obj) {
return Object.keys(obj).reduce(function(r, key) {
var k = key.includes('AVG') ? key.slice(4, -1) : key;
r[k] = obj[key];
return r;
}, {});
});
console.log(result);

Get first element of a sparse JavaScript array

I have an array of objects in javascript. I use jquery.
How do i get the first element in the array? I cant use the array index - as I assign each elements index when I am adding the objects to the array. So the indexes arent 0, 1, 2 etc.
Just need to get the first element of the array?
If you don't use sequentially numbered elements, you'll have to loop through until you hit the first one:
var firstIndex = 0;
while (firstIndex < myarray.length && myarray[firstIndex] === undefined) {
firstIndex++;
}
if (firstIndex < myarray.length) {
var firstElement = myarray[firstIndex];
} else {
// no elements.
}
or some equivalently silly construction. This gets you the first item's index, which you might or might not care about it.
If this is something you need to do often, you should keep a lookaside reference to the current first valid index, so this becomes an O(1) operation instead of O(n) every time. If you're frequently needing to iterate through a truly sparse array, consider another data structure, like keeping an object alongside it that back-maps ordinal results to indexes, or something that fits your data.
The filter method works with sparse arrays.
var first = array.filter(x => true)[0];
Have you considered:
function getFirstIndex(array){
var result;
if(array instanceof Array){
for(var i in array){
result = i;
break;
}
} else {
return null;
}
return result;
}
?
And as a way to get the last element in the array:
function getLastIndex(array){
var result;
if(array instanceof Array){
result = array.push("");
array.pop;
}
} else {
return null;
}
return result;
}
Neither of these uses jquery.
Object.keys(array)[0] returns the index (in String form) of the first element in the sparse array.
var array = [];
array[2] = true;
array[5] = undefined;
var keys = Object.keys(array); // => ["2", "5"]
var first = Number(keys[0]); // => 2
var last = Number(keys[keys.length - 1]); // => 5
I was also facing a similar problem and was surprised that no one has considered the following:
var testArray = [];
testArray [1245]= 31;
testArray[2045] = 45;
for(index in testArray){
console.log(index+','+testArray[index])
}
The above will produce
1245,31
2045,45
If needed you could exist after the first iteration if all that was required but generally we need to know where in the array to begin.
This is a proposal with ES5 method with Array#some.
The code gets the first nonsparse element and the index. The iteration stops immediately with returning true in the callback:
var a = [, , 22, 33],
value,
index;
a.some(function (v, i) {
value = v;
index = i;
return true;
});
console.log(index, value);
If you find yourself needing to do manipulation of arrays a lot, you might be interested in the Underscore library. It provides utility methods for manipulating arrays, for example compact:
var yourArray = [];
yourArray[10] = "foo";
var firstValue = _.compact(yourArray)[0];
However, it does sound like you are doing something strange when you are constructing your array. Perhaps Array.push would help you out?

Categories