Remove objects from array of object in javascript - javascript

I'm trying to remove objects from an array of object using a delta data i'm getting from server. I'm using underscore in my project.
Is there a straight forward way to do this, rather going with looping and assigning ?
Main Array
var input = [
{name: "AAA", id: 845,status:1},
{name: "BBB", id: 839,status:1},
{name: "CCC", id: 854,status:1}
];
Tobe Removed
var deltadata = [
{name: "AAA", id: 845,status:0},
{name: "BBB", id: 839,status:0}
];
Expected output
var finaldata = [
{name: "CCC", id: 854,status:1}
]

Try this
var finaldata = _.filter(input, function(item) {
return !(_.findWhere(deltadata, {id: item.id}));
});
It does assume that you have unique ID's. Maybe you can come up with something better.

Here's a simple solution. As others have mentioned, I don't think this is possible without a loop. You could also add checks for status and name in the condition, as this just compares IDs.
var finaldata = input.filter(function(o) {
for (var i = 0; i < deltadata.length; i++)
if (deltadata[i].id === o.id) return false;
return true;
});

A simple filter will do it:
var finaldata = _.filter(input, function(o) {
return _.findWhere(deltadata, o) === undefined;
});
A little more efficient than the findWhere would be creating a lookup map with ids to remove, and then filtering by that:
var idsToRemove = _.reduce(deltadata, function(m, o) {
m[o.id] = true;
return m;
}, {});
var finaldata = _.reject(input, function(o) { return o.id in idsToRemove; });

Related

retriving values from javascript object and then convert it to one object

I have a problem! I am creating an rating app, and I have come across a problem that I don't know how to solve. The app is react native based so I am using JavaScript.
The problem is that I have multiple objects that are almost the same, I want to take out the average value from the values of the "same" objects and create a new one with the average value as the new value of the newly created object
This array in my code comes as a parameter to a function
var arr = [
{"name":"foo","value":2},
{"name":"foo","value":5},
{"name":"foo","value":2},
{"name":"bar","value":2},
{"name":"bar","value":1}
]
and the result I want is
var newArr = [
{"name":"foo","value":3},
{"name":"bar","value":1.5},
]
If anyone can help me I would appreciate that so much!
this is not my exact code of course so that others can take help from this as well, if you want my code to help me I can send it if that's needed
If you have any questions I'm more than happy to answer those
Iterate the array with Array.reduce(), and collect to object using the name values as the key. Sum the Value attribute of each name to total, and increment count.
Convert the object back to array using Object.values(). Iterate the new array with Array.map(), and get the average value by dividing the total by count:
const arr = [{"name":"foo","Value":2},{"name":"foo","Value":5},{"name":"foo","Value":2},{"name":"bar","Value":2},{"name":"bar","Value":1}];
const result = Object.values(arr.reduce((r, { name, Value }) => {
if(!r[name]) r[name] = { name, total: 0, count: 0 };
r[name].total += Value;
r[name].count += 1;
return r;
}, Object.create(null)))
.map(({ name, total, count }) => ({
name,
value: total / count
}));
console.log(result);
I guess you need something like this :
let arr = [
{name: "foo", Value: 2},
{name: "foo", Value: 5},
{name: "foo", Value: 2},
{name: "bar", Value: 2},
{name: "bar", Value: 1}
];
let tempArr = [];
arr.map((e, i) => {
tempArr[e.name] = tempArr[e.name] || [];
tempArr[e.name].push(e.Value);
});
var newArr = [];
$.each(Object.keys(tempArr), (i, e) => {
let sum = tempArr[e].reduce((pv, cv) => pv+cv, 0);
newArr.push({name: e, value: sum/tempArr[e].length});
});
console.log(newArr);
Good luck !
If you have the option of using underscore.js, the problem becomes simple:
group the objects in arr by name
for each group calculate the average of items by reducing to the sum of their values and dividing by group length
map each group to a single object containing the name and the average
var arr = [
obj = {
name: "foo",
Value: 2
},
obj = {
name: "foo",
Value: 5
},
obj = {
name: "foo",
Value: 2
},
obj = {
name: "bar",
Value: 2
},
obj = {
name: "bar",
Value: 1
}
]
// chain the sequence of operations
var result = _.chain(arr)
// group the array by name
.groupBy('name')
// process each group
.map(function(group, name) {
// calculate the average of items in the group
var avg = (group.length > 0) ? _.reduce(group, function(sum, item) { return sum + item.Value }, 0) / group.length : 0;
return {
name: name,
value: avg
}
})
.value();
console.log(result);
<script src="http://underscorejs.org/underscore-min.js"></script>
In arr you have the property Value and in newArr you have the property value, so I‘ll assume it to be value both. Please change if wished otherwise.
var map = {};
for(i = 0; i < arr.length; i++)
{
if(typeof map[arr[i].name] == ‘undefined‘)
{
map[arr[i].name] = {
name: arr[i].name,
value: arr[i].value,
count: 1,
};
} else {
map[arr[i].name].value += arr[i].value;
map[arr[i].name].count++;
}
var newArr = [];
for(prop in map)
{
map[prop].value /= map[prop].count;
newArr.push({
name: prop,
value: map[prop].value
});
}
delete map;

_lodash orderBy() and sortBy() sort object based on a property 'weight'

For those that already voted(negative), i show what i needed!
var obj = {
item_1: {name:'aaa',weight:4},
item_2: {name:'ddd',weight:2},
item_5: {name:'eee',weight:0},
item_3: {name:'ccc',weight:3},
item_6: {name:'ccc',weight:23},
item_4: {name:'eee',weight:1},
}
var arr = _.toPairs(obj)
console.log(arr)
var sortedArr = arr.sort(function(a,b){ return b[1].weight - a[1].weight})
console.log(sortedArr)
var sortedObj = _.fromPairs(sortedArr)
console.log(JSON.stringify(sortedObj))
live link here: sort Object based on 'weight'property
please study before you judge.
i have an object array like this:
var obj = {
item_1: {name:'aaa',weight:4},
item_2: {name:'ddd',weight:2},
item_3: {name:'ccc',weight:3},
item_4: {name:'eee',weight:1},
}
When i run: _.orderBy or _.sortBy()
e.g. : _.orderBy(obj,['weight']) .
i get the sorted array , but without the initial keys
0: {name: "eee", weight: 1}
1: {name: "ddd", weight: 2}
2: {name: "ccc", weight: 3}
3: {name: "aaa", weight: 4}
But i need the original keys item_1, item_2 etc.
Can anyone give a hand ? Thanks.
See if this will help you. You may delete the extra key property if needed.
var obj = {
item_1: {name:'aaa',weight:4},
item_2: {name:'ddd',weight:2},
item_5: {name:'eee',weight:0},
item_3: {name:'ccc',weight:3},
item_6: {name:'ccc',weight:23},
item_4: {name:'eee',weight:1},
}
function buildItem(item, key) {
var newItem = { key: key };
newItem[key] = item;
return newItem;
}
function byWeight(item) {
return item[item.key].weight;
}
var arr = _(obj).map(buildItem).sortBy(byWeight).value();
console.log(arr);

array map, map array as a key of an array

I know the title might sounds confusing, but i'm stuck for an hour using $.each. Basically I have 2 arrays
[{"section_name":"abc","id":1},{"section_name":"xyz","id":2}];
and [{"toy":"car","section_id":1},{"tool":"knife","section_id":1},{"weapons":"cutter","section_id":2}];
How do I put one into another as a new property key like
[{
"section_name": "abc",
"id": 1,
"new_property_name": [{
"toy": "car"
}, {
"tool": "knife"
}]
}, {
"section_name": "xyz",
"id": 2,
"new_property_name": [{
"weapon": "cutter"
}]
}]
ES6 Solution :
const arr = [{"section_name":"abc","id":1},{"section_name":"xyz","id":2}];
const arr2 = [{"toy":"car","id":1},{"tool":"knife","id":1},{"weapons":"cutter","id":2}];
const res = arr.map((section,index) => {
section.new_property_name = arr2.filter(item => item.id === section.id);
return section;
});
EDIT : Like georg mentionned in the comments, the solution above is actually mutating arr, it modifies the original arr (if you log the arr after mapping it, you will see it has changed, mutated the arr and have the new_property_name). It makes the .map() useless, a simple forEach() is indeed more appropriate and save one line.
arr.forEach(section => {
section.new_property_name = arr2.filter(item => item.id === section.id));
});
try this
var data1 = [{"section_name":"abc","id":1},{"section_name":"xyz","id":2}];
var data2 = [{"toy":"car","id":1},{"tool":"knife","id":1},{"weapons":"cutter","id":2}];
var map = {};
//first iterate data1 the create a map of all the objects by its ids
data1.forEach( function( obj ){ map[ obj.id ] = obj });
//Iterate data2 and populate the new_property_name of all the ids
data2.forEach( function(obj){
var id = obj.id;
map[ id ].new_property_name = map[ id ].new_property_name || [];
delete obj.id;
map[ id ].new_property_name.push( obj );
});
//just get only the values from the map
var output = Object.keys(map).map(function(key){ return map[ key ] });
console.log(output);
You could use ah hash table for look up and build a new object for inserting into the new_property_name array.
var array1 = [{ "section_name": "abc", "id": 1 }, { "section_name": "xyz", "id": 2 }],
array2 = [{ "toy": "car", "section_id": 1 }, { "tool": "knife", "section_id": 1 }, { "weapons": "cutter", "section_id": 2 }],
hash = Object.create(null);
array1.forEach(function (a) {
a.new_property_name = [];
hash[a.id] = a;
});
array2.forEach(function (a) {
hash[a.section_id].new_property_name.push(Object.keys(a).reduce(function (r, k) {
if (k !== 'section_id') {
r[k] = a[k];
}
return r;
}, {}));
});
console.log(array1);
Seems like by using Jquery $.merge() Function you can achieve what you need. Then we have concat function too which can be used to merge one array with another.
Use Object.assign()
In your case you can do it like Object.assign(array1[0], array2[0]).
It's very good for combining objects, so in your case you just need to combine your objects within the array.
Example of code:
var objA = [{"section_name":"abc","id":1},{"section_name":"xyz","id":2}];
var objB = [{"toy":"car","section_id":1},{"tool":"knife","section_id":1},{"weapons":"cutter","section_id":2}];
var objC = Object.assign({},objA[0],objB[0]);
console.log(JSON.stringify(objC));// {"section_name":"abc","id":1,"toy":"car","section_id":1}
For more info, you can refer here: Object.assign()
var firstArray = [{"section_name":"abc","id":1},{"section_name":"xyz","id":2}],
secondArray = [{"toy":"car","section_id":1},{"tool":"knife","section_id":1},{"weapons":"cutter","section_id":2}];
var hash = Object.create(null);
firstArray.forEach(s => {
hash[s.id] = s;
s['new_property_name'] = [];
});
secondArray.forEach(i => hash[i['section_id']]['new_property_name'].push(i));
console.log(firstArray);

Get parent array key in deep nested object using lodash

I'm using Lodash JavaScript library in my project and have a problem in getting the parent array key object filtered object:
I've the following data:
var data = {
5: [{
id: "3",
label: "Manish"
}, {
id: "6",
label: "Rahul"
}, {
id: "7",
label: "Vikash"
}],
8: [{
id: "16",
label: "Pankaj"
}, {
id: "45",
label: "Akash"
}],
9: [{
id: "15",
label: "Sunil"
}]
}
My requirement is if I've the array of [6,16] then I want a new result array containing values 5,8 because these two array keys have objects which contain id:"6" and id:"16"
I tried it using _.flatten and _.pick method but could not work. I used the following code;
var list = [];
_.each(data, function(item){
list.push(_.omit(item, 'id'));
list.push(_.flatten(_.pick(item, 'id')));
});
var result = _.flatten(list);
console.log(result);
var res = _([6, 16]).map(function(id){
return _.findKey(data, function(arr){
return _.some(arr, {id: new String(id)});
})
}).compact().uniq().value();
If simple javascript solution is okay with you then
var searchId=[6,16];
var newArr = [];
for ( key in data ){
data[key].forEach( function(innerValue){
if ( searchId.indexOf( Number(innerValue.id) ) != -1 ) newArr.push( key );
} );
}
console.log(newArr);
try this:
( hope im not missing some syntax )
var result = [];
var filterArray = [6,16];
_.each(filterArray, function(item){
_.merge(result,_.filter(data, function(o) { return _.contains(o,{id:item}) }));
});
Using _.pickBy this problem is solved simply:
var myArr = [6, 16]
var res = _.pickBy(data, function (value) {
return _(value).map('id').map(_.toNumber).intersection(myArr).size();
});
console.log(res)
https://jsfiddle.net/7s4s7h3w/

New array of objects by comparing and pushing unique objects

I have 2 arrays of objects exclude and people, I want to create a new object by checking exclude properties against people properties and only adding objects in people that don't feature in exclude. So far my attempt is a little wild and wondering if someone can help make things a little better or offer a nicer solution?
Fiddle http://jsfiddle.net/kyllle/k02jw2j0/
JS
var exclude = [{
id: 1,
name: 'John'
}];
var peopleArr = [{
id: 1,
name: 'John'
}, {
id: 2,
name: 'James'
}, {
id: 3,
name: 'Simon'
}];
var myObj = [];
for (key in peopleArr) {
for (k in exclude) {
if (JSON.stringify(peopleArr[key]) != JSON.stringify(exclude[k])) {
console.log(peopleArr[key]);
myObj.push(peopleArr[key]);
}
}
}
console.log(myObj);
Under the assumption that exclude can have multiple items, I would use a combination of filter() and forEach() :
var newArray = peopleArr.filter(function(person) {
include = true;
exclude.forEach(function(exl) {
if (JSON.stringify(exl) == JSON.stringify(person)) {
include = false;
return;
}
})
if (include) return person;
})
forked fiddle -> http://jsfiddle.net/6c24rte8/
You repeat some JSON.stringify calls.
You can convert your arrays to JSON once, and then reuse it. Also, you can replace your push by Array.prototype.filter.
var excludeJson = exclude.map(JSON.stringify);
peopleArr = peopleArr.filter(function(x) {
return excludeJson.indexOf(JSON.stringify(x)) === -1;
});
Here is the working snippet:
var exclude = [{
id: 1,
name: 'John'
}];
var peopleArr = [{
id: 1,
name: 'John'
}, {
id: 2,
name: 'James'
}, {
id: 3,
name: 'Simon'
}];
var excludeJson = exclude.map(JSON.stringify);
peopleArr = peopleArr.filter(function(x) {
return excludeJson.indexOf(JSON.stringify(x)) === -1;
});
document.body.innerText = JSON.stringify(peopleArr);
This can be achieved with .filter and .findIndex
var myObj = peopleArr.filter(function(person){
var idx = exclude.findIndex(function(exc) { return person.id == exc.id && person.name == exc.name; });
return idx == -1; // means current person not found in the exclude list
});
I have explicitly compared the actual properties back to the original, there is nothing particularly wrong with your original way of comparing the stringified version (JSON.stringify(e) == JSON.stringify(x) could be used in my example)

Categories