I have an array with multiple objects
arr = [
{name: 'xyz',
age: 13,
},
{name: 'abc',
age: 15,
},
{name: 'abc',
age: 15,
}]
how do I find the duplicate in this array and remove the object that is duplicated in the array? They are all in one array.
Apologies. I just realized what I am trying to do is, remove the object entirely if there's a duplicate in one key... so if the age is similar, I will remove object name "def". Is this possible?
arr = [
{name: 'xyz',
entry: 1,
age: 13,
},
{name: 'abc',
entry: 2,
age: 15,
},
{name: 'def',
age: 13,
entry: 3
}]
You could achieve this by the following steps:
transform each element into an object that is key-sorted, this will make objects consistent in terms of key-value pairs order, which will help us in the next step
map the array into JSON-stringified value, and store it into a Set(), which would help us store only unique stringified objects
turn the Set() back into array
map the array back into objects by JSON.parse() each element
const arr = [
{ name: "xyz", age: 13 },
{ age: 15, name: "abc" },
{ name: "abc", age: 15 },
]
const sortKeys = obj =>
Object.fromEntries(
Object.entries(obj).sort((keyValuePairA, keyValuePairB) =>
keyValuePairA[0].localeCompare(keyValuePairB[0])
)
)
const res = Array.from(
arr
.map(sortKeys)
.map(el => JSON.stringify(el))
.reduce((set, el) => set.add(el), new Set())
).map(el => JSON.parse(el))
console.log(res)
References
Set
Object.entries()
Object.fromEntries()
Related
I have 2 dimensional array myArray:
[
[ '567576', 'John', 'Doe' ],
[ '098897', 'John', 'Doe' ],
[ '543539', 'John', 'Doe' ],
[ '234235', 'John', 'Doe' ],
[ '345348', 'John', 'Doe' ],
[ '432574', 'John', 'Doe' ]
]
Is it possible to create a new array from myArray starting from a certain first value?
For example create a new array starting from id 543539. Anything above the array containing 543539 will not be added.
You can make use of findIndex() which returns the index of the first item that matches the condition.
Combine it with slice() to cut your array at the specific position:
const myArray = [
['567576', 'John', 'Doe'],
['098897', 'John', 'Doe'],
['543539', 'John', 'Doe'],
['234235', 'John', 'Doe'],
['345348', 'John', 'Doe'],
['432574', 'John', 'Doe']
]
console.log(myArray.slice(myArray.findIndex(item => item[0] === "543539")));
Sure, assuming all the internal arrays are structured the same way, you can do something like let newArray = myArray.filter(innerArray => Number(innerArray[0]) > 543539)
Edit: This is assuming you want all subarrays where the first item is a number larger than 54539, as opposed to finding all of the subarrays that physically follow the first occurrence of a subarray with 54539 as the first value
Yes, that is possible and straightforward process.
You can use the javascript map method which returns a new array
newArray = myArray.map(item=> item[0])
const obj = {
obj1: [{
name: 'Max',
age: 25
}]
}
Object.values(obj).map(obj => console.log(obj.obj1.name))
Uncaught TypeError: Cannot read property 'name' of undefined. I need to get that name
If you are just trying to loop through the object values, using forEach instead of the map is a good idea. Map returns a new array but forEach doesn't. Also, Object.values() will return an array of all the values in the object(each value is an array of objects in this case). Therefore, using 2 forEach loops makes the task easier.
const obj = {
obj1: [{
name: 'Max',
age: 25
}],
obj2: [{
name: 'Min',
age: 26
}]
}
Object.values(obj).forEach(mainObj => mainObj.forEach(obj => console.log(obj.name )))
You are trying to access the wrong key. Your object has a key obj1 which is an array. You have to loop through that array as well.
const obj = {
obj1: [{
name: 'Max',
age: 25
}],
obj2: [{
name: 'Min',
age: 24
}]
}
var objectValuesArr = Object.values(obj)
var particularObj = objectValuesArr.map(obj => obj.forEach(obj => console.log(obj.name)))
This question already has answers here:
Javascript - convert array of arrays into array of objects with prefilled values
(4 answers)
Closed 2 years ago.
I Have some array like below:
[
[
'James',
23,
'male'
],
[
'Britney',
45,
'female'
]
]
I would like to turn that into a json looking like:
[
{
'name': 'James',
'age': 23,
'gender'': 'male'
},
{
'name': 'Britney',
'age': 45,
'gender'': 'female'
}
]
I understand the json stringify part to convert the array to json but not sure how to create the keys for the values in an efficient way. Any help is greatly appreciated.
Use map, then destruct the array and return an object.
const arr = [
[
'James',
23,
'male'
],
[
'Britney',
45,
'female'
]
]
const res = arr.map(([name, age, gender]) => ({
name,
age,
gender
}))
console.log(res);
You can do this with map with proper destructuring(for shortcut):
var a=[ [ 'James', 23, 'male' ], [ 'Britney',45,'female']];
var result = a.map(([name,age,gender])=>({name, age, gender}));
console.log(result);
I have a javascript object as follows.
{
name: "tom",
age: 5,
fruits: [
{name: "apple",qty: 4},
{name: "orange",qty: 13},
{name: "banana",qty: 3}
]
}
I am trying to convert this object into an object given below.
{
name: "tom",
age: 5,
apple: 4,
orange: 13,
banana: 3
}
How do I achieve this? I have tried to loop through the fruits array but I am unable to find a way to create a variable with the fruit name and assign the qty to it.
You can use forEach and delete to clean up the old key. Take care not to overwrite keys accidentally, though (you could test if (e.name in obj) as a safety check).
const obj = {
name: "tom",
age: 5,
fruits: [
{name: "apple",qty: 4},
{name: "orange",qty: 13},
{name: "banana",qty: 3}
]
};
obj.fruits.forEach(e => obj[e.name] = e.qty);
delete obj.fruits;
console.log(obj);
you can use below simple code
var b={
name: "tom",
age: 5}
for (var i = 0; i<a.fruits.length; i++) {
b[a.fruits[i].name]=a.fruits[i].qty;
}
This a generic function to convert if you don't want to mutate the original object. Destructure the object to get fruits and rest of the properties separately. Then you can use Object.assign() and map to to create a new object.
let obj = {
name: "tom",
age: 5,
fruits: [
{name: "apple",qty: 4},
{name: "orange",qty: 13},
{name: "banana",qty: 3}
]
}
const converter = ({ fruits, ...rest }) =>
Object.assign(rest, ...fruits.map(({ name, qty }) => ({ [name]: qty })))
console.log(converter(obj))
I have 2 arrays of objects, they each have an id in common. I need a property from objects of array 2 added to objects array 1, if they have matching ids.
Array 1:
[
{
id: 1,
name: tom,
age: 24
},
{
id: 2,
name: tim,
age: 25
},
{
id: 3,
name: jack,
age: 24
},
]
Array 2:
[
{
id: 1,
gender: male,
eyeColour: blue,
weight: 150
},
{
id: 2,
gender: male,
eyeColour: green,
weight: 175
},
{
id: 3,
gender: male,
eyeColour: hazel,
weight: 200
},
]
Desired Outcome:
[
{
id: 1,
name: tom,
age: 24,
eyeColour: blue,
},
{
id: 2,
name: tim,
age: 25,
eyeColour: green,
},
{
id: 3,
name: jack,
age: 24,
eyeColour: hazel,
},
]
I tried using lodash _.merge function but then I end up with all properties into one array, when I only want eyeColour added.
Lodash remains a highly useful bag of utilities, but with the advent of ES6 some of its use cases are less compelling.
For each object (person) in the first array, find the object in the second array with matching ID (see function findPerson). Then merge the two.
function update(array1, array2) {
var findPerson = id => array2.find(person => person.id === id);
array1.forEach(person => Object.assign(person, findPerson(person.id));
}
For non-ES6 environments, rewrite arrow functions using traditional syntax. If Array#find is not available, write your own or use some equivalent. For Object.assign, if you prefer use your own equivalent such as _.extend.
This will merge all properties from array2 into array1. To only merge eyeColour:
function update(array1, array2) {
var findPerson = id => array2.find(person => person.id === id);
array1.forEach(person => {
var person2 = findPerson(person.id));
var {eyeColour} = person2;
Object.assign(person, {eyeColour});
});
}
Just noticed Paul answered while I was working on my answer but I'll add my very similar code anyway:
var getEyeColour = function (el) { return _.pick(el, 'eyeColour'); }
var out = _.merge(arr1, _.map(arr2, getEyeColour));
DEMO
You can use pick to get only the properties you want before merging:
var result = _.merge( arr1, _.map( arr2, function( obj ) {
return _.pick( obj, 'id', 'eyeColour' );
}));
A solution in plain Javascript
This is a more generic solution for merging two arrays which have different properties to union in one object with a common key and some properties to add.
var array1 = [{ id: 1, name: 'tom', age: 24 }, { id: 2, name: 'tim', age: 25 }, { id: 3, name: 'jack', age: 24 }, ],
array2 = [{ id: 1, gender: 'male', eyeColour: 'blue', weight: 150 }, { id: 2, gender: 'male', eyeColour: 'green', weight: 175 }, { id: 3, gender: 'male', eyeColour: 'hazel', weight: 200 }, ];
function merge(a, b, id, keys) {
var array = [], object = {};
function m(c) {
if (!object[c[id]]) {
object[c[id]] = {};
object[c[id]][id] = c[id];
array.push(object[c[id]]);
}
keys.forEach(function (k) {
if (k in c) {
object[c[id]][k] = c[k];
}
});
}
a.forEach(m);
b.forEach(m);
return array;
}
document.write('<pre>' + JSON.stringify(merge(array1, array2, 'id', ['name', 'age', 'eyeColour']), 0, 4) + '</pre>');
I was looking for the same, but I want to match Id before merging
And in my case, second array may have different number of items, finally I came with this:
var out = arr1.map(x => {
return { ...x, eyeColour: arr2.find(y => x.id === y.id)?.eyeColour }
});