How to remove dublicate values from array of objects using javaScript? [duplicate] - javascript

This question already has answers here:
Get all unique values in a JavaScript array (remove duplicates)
(91 answers)
Closed 1 year ago.
I have this array of objects, my aim is to remove dublicate values from values array, I want the result to be [{name:'test1', values:['35,5', '35,2','35,3']}, {name:'test2', values:['33,2', '34,3', '32,5']}]
I have tried following solution but it does not works, Do you have any suggestions? Thanks in advance
let arr = [{name:'test1', values:['35,5', '35,2', '35,2', '35,3', '35,5']},
{name:'test2', values:['35,1', '35,1', '33,2', '34,3', '32,5']}]
let uniqueArray = arr.values.filter(function(item, pos) {
return arr.values.indexOf(item.values) == pos;
})
console.log(uniqueArray)
}
}

You can easily remove duplicates from an Array by creating a new Set based off it.
Set objects are collections of values. You can iterate through the elements of a set in insertion order. A value in the Set may only occur once; it is unique in the Set's collection
If you want the result in an array, just use spread syntax for that, for example:
let arr = [{
name: 'test1',
values: ['35,5', '35,2', '35,2', '35,3', '35,5']
},
{
name: 'test2',
values: ['35,1', '35,1', '33,2', '34,3', '32,5']
}
];
const uniqueArr = arr.reduce((accum, el) => {
// Copy all the original object properties to a new object
const obj = {
...el
};
// Remove the duplicates from values by creating a Set structure
// and then spread that back into an empty array
obj.values = [...new Set(obj.values)];
accum.push(obj);
return accum;
}, []);
uniqueArr.forEach(el => console.dir(el));

Related

Create a array of objects by grouping objects conditionally [duplicate]

This question already has answers here:
Group array items using object
(19 answers)
How can I group an array of objects by key?
(32 answers)
Closed last month.
I am trying to create a new array of objects by comparing two arrays.One array contains the ids to be compared and the other contains the dataset which should be compared with the first array are a new array of object must be created.
Let me explain this in detail
Consider array 1:
['1','2']
Array 2
[{name:'Linus',id:'1'},{name:'Anthony',id:'1'},{name:'Jake',id:'2'},{name:'Eva',id:'2'}]
What I am expecting as a output is:
[
{id:'1',users:[{name:'Linus',id:'1'},{name:'Anthony',id:'1'}]},
{id:'2',users:[{name:'Jake',id:'2'},{name:'Eva',id:'2'}
]
I am not sure what has to be done.
Something like this for example
const ids = ['1','2'];
const users = [{name:Linus,id:'1'},{name:Anthony,id:'1'},{name:Jake,id:'2'},{name:Eva,id:'2'}];
const groups = ids.map(id =>{
return {
id,
users: users.filter(u => u.id === id)
}
})
const groupBy = ['1','2'];
const data = [{name:'Linus',id:'1'},{name:'Anthony',id:'1'},{name:'Jake',id:'2'},{name:'Eva',id:'2'}];
const result = groupBy.map(id => {
return {
id,
users: data.filter(item => item.id == id),
}
})
console.log(result);
Try this code

Fill Out Array of Objects to add 0 values [duplicate]

This question already has answers here:
Make array objects all have the same keys
(5 answers)
Closed 1 year ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
I have a dynamic array which for downstream purposes needs to have all properties define for all objects.
If I have this array:
[
{"Header":"1","Apples":10},
{"Header":"2","Apples":10, "Oranges":153},
{"Header":"3","Oranges":280, "Pears":200},
{"Header":"4","Oranges":1165}
]
How do I fill it out to infill zero values for properties where they exist elsewhere in the array, but not in that object.
Essentially I need to up with this:
[
{"Header":"1","Apples":10, "Oranges":0, "Pears":0},
{"Header":"2","Apples":10, "Oranges":153, "Pears":0},
{"Header":"3","Apples":0, "Oranges":280, "Pears":200},
{"Header":"4","Apples":0, "Oranges":1165,"Pears":0}
]
Header property is essentially the id of each object
const arr = [
{"Header":"1","Apples":10},
{"Header":"2","Apples":10, "Oranges":153},
{"Header":"3","Oranges":280, "Pears":200},
{"Header":"4","Oranges":1165}
];
// get unique keys
let objWithAllProp = arr.reduce((acc, item) => ({...acc, ...item}));
// Get keys as an array and Create an object with all keys set to the default value to 0
let uniqueObjectWithAllProp = Object.keys(objWithAllProp).reduce((acc, key) => {
acc[key] = 0
return acc;
}, {});
// Replace all default values with original, so if key not present in original item, it will be available from uniqueObjectWithAllProp and value default to 0
let result = arr.map((item) => ({...uniqueObjectWithAllProp , ...item}));
console.log(result);
You can get all the existing property values by pushing each item's properties to an array (with Object.keys), then using Set and spread syntax to get the unique.
Then, map over each item in arr and in the loop, loop through the existing property values and check whether the current item has that property. If not, set the value of that property to 0.
const arr = [
{"Header":"1","Apples":10},
{"Header":"2","Apples":10, "Oranges":153},
{"Header":"3","Oranges":280, "Pears":200},
{"Header":"4","Oranges":1165}
]
const properties = [...new Set(arr.map(e => Object.keys(e)).flat())]
const result = arr.map(e => (properties.forEach(f => !e.hasOwnProperty(f) ? e[f] = 0 : ''), e))
console.log(result)

Removing the duplicates from an array of objects [duplicate]

This question already has answers here:
Get all unique values in a JavaScript array (remove duplicates)
(91 answers)
How to remove all duplicates from an array of objects?
(77 answers)
Remove duplicate values from an array of objects in javascript [duplicate]
(6 answers)
Closed 3 years ago.
Duplicate values are being storing into an array of object
Based on the given userID need to out the duplicate userId,
if it exist do nothing, else push that userIdinto the teamSocketsList array
But with the below piece of code duplicate values are being stored into an array teamSocketsList
var TeamUser = {
userId : userID,
socketId : socket.id
}
var i = $.inArray( userID, teamSocketsList );
if(i == -1){
teamSocketsList.push(TeamUser);
}else{
teamSocketsList = jQuery.grep(teamSocketsList, function(value) {
return value != userID;
});
}
Actual Result:
[
{"userId":1,"socketId":"M8xzpi3O0cMHXe-dAAAK"},
{"userId":1,"socketId":"ZIbgYMLOda_R5QqvAAAN"},
{"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"},
{"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"}
]
Expected Result:
[
{"userId":1,"socketId":"M8xzpi3O0cMHXe-dAAAK"},
{"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"},
]
Edit:
Here I'm expecting userID to be pushed in to an array teamSocketsList based on the condition, if at all the given userID matches in the present list should return false or do nothing. Otherwise, (iff, it's not at all included then) store it into an array with the auto-generated socketId value
The logic which I had tried to implement was to check whether if that array is empty or not and then, traverse all the elements in the array list so that whenever userID were given as an input it must check the condition and then push that element.
Based on the present answers put up, it'll store the duplicate values and then sort it on and assign it back to teamSocketsList, that's fine.
Along with already mentioned values/reduce, you can take advantage of Set():
const myArray = [
{"userId":1,"socketId":"M8xzpi3O0cMHXe-dAAAK"},
{"userId":1,"socketId":"ZIbgYMLOda_R5QqvAAAN"},
{"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"},
{"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"}
]
const unique = (arr, key) => {
const keys = new Set();
return arr.filter(el => !keys.has(el[key]) && keys.add(el[key]));
};
console.log(unique(myArray, "userId"));
In opposition to other response I can point out that with this method is easier to change array and key without adding code.
use reduce along with Object.values. create an object whose keys are userId. If the key does not exist, create the key and then use Object.values to get the required ouput.
const input = [
{"userId":1,"socketId":"M8xzpi3O0cMHXe-dAAAK"},
{"userId":1,"socketId":"ZIbgYMLOda_R5QqvAAAN"},
{"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"},
{"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"}
];
const output = Object.values(input.reduce((accu, {userId, socketId}) => {
if(!accu[userId]) accu[userId] = {userId, socketId};
return accu;
}, {}));
console.log(output);
How about this function where you pass in your array and the key to get your result
const convertArrayToObjecByID = ({ array, key }) =>
array.reduce((obj, item) => {
return { ...obj, [item[key]]: item };
}, {})
const input = [
{"userId":1,"socketId":"M8xzpi3O0cMHXe-dAAAK"},
{"userId":1,"socketId":"ZIbgYMLOda_R5QqvAAAN"},
{"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"},
{"userId":9,"socketId":"XAf1cepsLv-KDpn3AAAQ"}
]
const myObject = convertArrayToObjecByID({ array:input, key:'userId' })
console.log({myObject})
//then if you want it as an array
console.log(Object.keys(myObject).map(item => myObject[item]))
You can store your data in the object (key-value pair) and avoid adding duplicate data.
For example:
var teamSocketsList = {};
var TeamUser = {
userId : userID,
socketId : socket.id
}
teamSocketsList[TeamUser.userId] = TeamUser;
Then if you are adding new user to teamSocketsList, you can easily (without iterating through all elements in the array) check if there are teamUser with that id.
if(teamSocketsList[TeamUser.userId]) // team user exists in the list

Sort Javascript Object by Value [best practices?] [duplicate]

This question already has answers here:
Sort array of objects by string property value
(57 answers)
Closed 5 years ago.
Since there's no official way to sort an object by values, I'm guessing you either (1) Use an array instead or (2) Convert your object to an array using Object.entries(), sort it, then convert back to an object. But option (2) is technically unsafe since Javascript objects aren't supposed to have order.
Now I have a React app where I'm using Redux. I'm storing my data not as an array but as an object iterated by id values. This is what Redux suggests, and I would do it anyways, because of lookup times. I want to sort this redux data, so what I'm currently doing is option (2) of converting to array and then back to object. Which I don't really like.
My question is: Is this what everyone else does? Is it safe to sort an object?
Example:
const sortObject = (obj) => {
//return sorted object
}
var foo = {a: 234, b: 12, c: 130}
sortObject(foo) // {b: 12, c:130, a:234}
this is what I'm currently doing.
My object data structure looks something like this
obj = {
asjsd8jsadf: {
timestamp: 1234432832
},
nsduf8h3u29sjd: {
timestamp: 239084294
}
}
And this is how I'm sorting it
const sortObj = obj => {
const objArray = Object.entries(obj);
objArray.sort((a, b) => {
return a[1].timestamp < b[1].timestamp ? 1 : -1;
});
const objSorted = {};
objArray.forEach(key => {
objSorted[key[0]] = key[1];
});
return objSorted;
};
If you are using the Redux documentation for reference you should also have an array with all of the id's in it. Wouldn't it be easier to just sort that array and then use insertion sort when you add something to the state. Then you could use the sorted array to access the byId property of the state?

Javascript Array of objects get single value [duplicate]

This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Construct an array of elements from an array of objects? [duplicate]
(2 answers)
Closed 8 years ago.
Lets say I have an array of objects:
var employees=[]
employees[0]={name:"George", age:32, retiredate:"March 12, 2014"}
employees[1]={name:"Edward", age:17, retiredate:"June 2, 2023"}
employees[2]={name:"Christine", age:58, retiredate:"December 20, 2036"}
employees[3]={name:"Sarah", age:62, retiredate:"April 30, 2020"}
Is there an array function that will allow me to get one property as an array,
for example:
namesArray = employees.reduceToProperty('name'); // none existent function i made up!
// should return ["George","Edward","Christine","Sarah"]
I know how get the desired result with a loop, I am just hoping for an array function or combination of functions exist that can do this in one line.
var names = employees.map(function(i) {
return i.name;
});
names is now an array containing the name-properties of the objects.
Array.prototype.map maps one array to another:
var names = employees.map(function (val) {
return val.name;
});
// ['George', 'Edward', 'Christine', 'Sarah']
If you find yourself doing this frequently, you might consider using pluck from Underscore/Lo-Dash:
var listOfPropertyNames = _.pluck(list, 'propertyName');
underscorejs.org/#pluck
lodash.com/docs#pluck
If you don't want to do include a library, it is of course possible to write your own pluck for use on your code base:
function pluck(list, propertyName) {
return list.map(function(i) {
return i[propertyName];
});
}
And running it:
pluck([{name: 'a'}, {name: 'b'}], 'name');
["a", "b"]
You'll have to decide how to handle the edge cases like:
object in the list not having the property
an undefined being in the list
?

Categories

Resources