How do I extract duplicate values for objects in JavaScript? - javascript

I have the data from the database and I want to push the duplicate value to each array. I attach the exact example I want.
// origin data
const data = [
{
name: "Amy",
age: 17,
},
{
name: "Amy",
age: 17,
},
{
name: "Amy",
age: 17,
},
{
name: "Tommy",
age: 20,
},
{
name: "Tommy",
age: 20,
},
];
//result that I want to get
arr1 = [
{
name: "Amy",
age: 17,
},
{
name: "Amy",
age: 17,
},
{
name: "Amy",
age: 17,
},
];
arr2 = [
{
name: "Tommy",
age: 20,
},
{
name: "Tommy",
age: 20,
},
];
I want to create an array based on the name in this data and push it. Can anyone help?

One way would be to use reduce together with Object.values:
const data = [
{
name: "Amy",
age: 17,
},
{
name: "Amy",
age: 17,
},
{
name: "Amy",
age: 17,
},
{
name: "Tommy",
age: 20,
},
{
name: "Tommy",
age: 20,
}
];
const result = Object.values(data.reduce((acc, cur) => {
const key = `${cur.name}:${cur.age}`;
const prev = acc[key] || [];
return {
...acc,
[key]: prev.concat(cur)
}
}, {}));
console.log(result);

Related

how can I use Array.find() function to edit name and age properties inside specific object

I can go with find for editing one property like in this example. But I didn't find a syntax to edit more than one property.
const arr = [
{
id: 101,
name: “Jone”,
age: 1
},
{
id: 102,
name: “Jane”,
age: 2
},
{
id: 103,
name: “johnny”,
age: 3
}
];
console.log(arr);
arr.find(element => element.id == 101).name = “jimmy”
console.log(arr);
For example, using Object.assign
const arr = [
{
id: 101,
name: 'Jone',
age: 1
},
{
id: 102,
name: 'Jane',
age: 2
},
{
id: 103,
name: 'johnny',
age: 3
}
];
Object.assign(arr.find(el => el.id === 101), {
name: "Jimmy",
age: 5,
});
console.log(arr);
You can store the object that find returns and edit it as you need.
const arr = [
{
id: 101,
name: 'Jone',
age: 1
},
{
id: 102,
name: 'Jane',
age: 2
},
{
id: 103,
name: 'johnny',
age: 3
}
];
console.log(arr);
// ****
const found = arr.find(element => element.id == 101)
found.name = 'jimmy'
found.age = 54
// ****
console.log(arr);

Object of Arrays, return a new array with all name key valus [duplicate]

This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 1 year ago.
I am trying to return all the names from an object of arrays in to an new array just containing the names, but its not working, the if statement covers the issue of dealing with an empty array being passed here is the object, any suggestions much appreciated:-
const obj = [{
name: "Mitch",
age: 27,
language: "Javascript"
},
{
name: "Ant",
age: 28,
language: "Java"
},
{
name: "Natalia",
age: 29,
language: "C"
},
{
name: "Foluso",
age: 26,
language: "Ruby"
}
];
let newArray = [];
for (let i = 0; i <= obj.length; i++) {
newArray.push(obj.name);
if (obj => obj.length = 0) {
newArray = [];
}
}
return newArray;
}
const obj = [{
name: "Mitch",
age: 27,
language: "Javascript"
},
{
name: "Ant",
age: 28,
language: "Java"
},
{
name: "Natalia",
age: 29,
language: "C"
},
{
name: "Foluso",
age: 26,
language: "Ruby"
}
];
let new_array_of_names = obj.map(item=>item.name)
Here it is:
const obj = [
{ name: "Mitch", age: 27, language: "Javascript" },
{ name: "Ant", age: 28, language: "Java" },
{ name: "Natalia", age: 29, language: "C" },
{ name: "Foluso", age: 26, language: "Ruby" }
];
const names = obj.map(x => x.name)
console.log('names', names)

JavaScript sort an array of objects based array of properties

I have for example this dataset:
const order = [
{ key: "job", direction: "ascending" },
{ key: "age", direction: "descending" },
];
const records = [
{ name: "christian", age: 40, job: "developer" },
{ name: "andrew", age: 48, job: "developer" },
{ name: "elisabeth", age: 31, job: "floor manager" },
{ name: "oscar", age: 61, job: "floor manager" },
{ name: "gisela", age: 51, job: "area manager" },
{ name: "buffy", age: 27, job: "trainee" },
{ name: "carl", age: 23, job: "trainee" },
];
I need to sort the records array according to the criteria from order array.
I ended up with this solution:
const sorted = records.sort(
(recordA, recordB) =>
recordA.job.localeCompare(recordB.job) || recordA.age - recordB.age
);
But I cant understand how can I use the order array instead of hardcoded the job and age properties. The order array can have many properties.
You could take a closure over the wanted order and check the value if finite then return the delta or treat the values as string.
Inside sorting function iterate as long as the return value is falsy and take this value as return value for sorting.
const
sortBy = order => (a, b) => {
let r;
order.some(({ key, direction }) => r = (isFinite(a[key]) && isFinite(b[key])
? a[key] - b[key]
: a[key].toString().localeCompare(b[key])
) * (direction === 'ascending' || -1))
return r;
},
records = [{ name: "christian", age: 40, job: "developer" }, { name: "andrew", age: 48, job: "developer" }, { name: "elisabeth", age: 31, job: "floor manager" }, { name: "oscar", age: 61, job: "floor manager" }, { name: "gisela", age: 51, job: "area manager" }, { name: "buffy", age: 27, job: "trainee" }, { name: "carl", age: 23, job: "trainee" }],
order = [{ key: "job", direction: "ascending" }, { key: "age", direction: "descending" }];
console.log(records.sort(sortBy(order)));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Just loop over the order data and make the comparisons:
let order = [{ key: "job", direction: "ascending" }, { key: "age", direction: "descending" }];
let records = [{ name: "christian", age: 40, job: "developer" }, { name: "andrew", age: 48, job: "developer" }, { name: "elisabeth", age: 31, job: "floor manager" }, { name: "oscar", age: 61, job: "floor manager" }, { name: "gisela", age: 51, job: "area manager" }, { name: "buffy", age: 27, job: "trainee" }, { name: "carl", age: 23, job: "trainee" }];
records.sort(function (a, b) {
for (let {key, direction} of order) {
if (a[key] !== b[key]) return (direction[0] === "a") === (a[key] < b[key]) ? -1 : 1;
}
return 0;
});
console.log(records);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You could use (a[key] > b[key]) - (a[key] < b[key]) to compare two values either lexically or numerically (if both are numbers). This could then be used like:
const order = [
{ key: "job", direction: "ascending" },
{ key: "age", direction: "descending" },
];
const records = [
{ name: "christian", age: 40, job: "developer" },
{ name: "andrew", age: 48, job: "developer" },
{ name: "elisabeth", age: 31, job: "floor manager" },
{ name: "oscar", age: 61, job: "floor manager" },
{ name: "gisela", age: 51, job: "area manager" },
{ name: "buffy", age: 27, job: "trainee" },
{ name: "carl", age: 23, job: "trainee" },
];
const compare = (key) => (a, b) => (a[key] > b[key]) - (a[key] < b[key]);
const or = (a, b) => (...v) => a(...v) || b(...v);
const sorter = order.map(it => compare(it.key)).reduce(or);
const sorted = records.sort(sorter);
console.log(sorted);
The implementation of direction was left to the reader

How to convert one field in a multidimensional array to lowercase?

For example if I have a multidimensional array like this:
const coWorkers = [
{ name: "Jack", age: 40, resident_state: "Wyoming" },
{ name: "Mary", age: 30, resident_state: "New Jersey" },
{ name: "Kate", age: 20, resident_state: "Florida" },
{ name: "Gerome", age: 50, resident_state: "Texas" },
];
and I want to create a function to turn one field in this array (ex: state) to lowercase, how would I go about doing so?
I have tried this:
const coWorkers = [
{ name: "Jack", age: 40, resident_state: "Wyoming" },
{ name: "Mary", age: 30, resident_state: "New Jersey" },
{ name: "Kate", age: 20, resident_state: "Florida" },
{ name: "Gerome", age: 50, resident_state: "Texas" },
];
function lowerCaseStates(coWorkers.resident_state){
lowerCasing = function() {
return coWorkers.resident_state.toLowerCase();
}
lowercaseStates = coWorkers.map(lowerCasing);
console.log(lowercaseStates)
}
lowerCaseStates()
How would I go about doing this while not replacing each cell in the array individually?
You cannot have a dotted parameter in the function (and do not need it if you access it inside the function
just run directly on the string
You do not have a multidimensional array. You have an object array
You can use a function to process the complete array in one map statement - I use the ...rest to just copy the other items we are not interested in
Note I have to wrap the object in () if I do not have => {} in the arrow function
const coWorkers = [
{ name: "Jack", age: 40, resident_state: "Wyoming" },
{ name: "Mary", age: 30, resident_state: "New Jersey" },
{ name: "Kate", age: 20, resident_state: "Florida" },
{ name: "Gerome", age: 50, resident_state: "Texas" }
];
const lowerCase = ({resident_state, ...rest }) =>
({ resident_state: resident_state.toLowerCase(), ...rest });
const coWorkersLowerCase = coWorkers
.map(lowerCase)
console.log(coWorkersLowerCase)
If you want to modify the original, you can use a forEach
const coWorkers = [
{ name: "Jack", age: 40, resident_state: "Wyoming" },
{ name: "Mary", age: 30, resident_state: "New Jersey" },
{ name: "Kate", age: 20, resident_state: "Florida" },
{ name: "Gerome", age: 50, resident_state: "Texas" }
];
coWorkers.forEach(item => item.resident_state = item.resident_state.toLowerCase())
console.log(coWorkers)
Hi i would go like this
coWorkers.map(x=>{
x.resident_state=x.resident_state.toLowerCase();
return x
})

Convert some fields of array of objects to json data in javascript?

I have an array of objects as mentioned below,
var arraydata =[
{ id:1, name:"Abraham", age:20,gender:"male"},
{ id:2, name:"Annie", age:25,gender:"female"},
{ id:3, name:"Ryan", age:40,gender:"male"},
{ id:4, name:"Wayne", age:31,gender:"male"},
{ id:5, name:"Paul", age:45,gender:"male"}
];
how to convert this to a JSON data, which has only "id" and "name" field?
syntax is wrong age=20,gender="male" change it to age:20,gender:"male"
var arraydata =[
{ id:1, name:"Abraham", age: 20, gender:"male"},
{ id:2, name:"Annie", age: 25, gender:"female"},
{ id:3, name:"Ryan", age: 28, gender:"male"},
{ id:4, name:"Wayne", age: 19, gender:"male"},
{ id:5, name:"Paul", age: 45,gender:"male"}
];
var ans= arraydata.map(function(a){
return {id:a.id,name:a.name};
})
console.log(ans);
You can use the delete operator which remove a property from an object.
var arraydata = [{
id: 1,
name: "Abraham",
age : 20,
gender : "male"
}, {
id: 2,
name: "Annie",
age : 25,
gender : "female"
}, {
id: 3,
name: "Ryan",
age : 40,
gender : "male"
}, {
id: 4,
name: "Wayne",
age : 31,
gender : "male"
}, {
id: 5,
name: "Paul",
age : 45,
gender : "male"
}];
arraydata.forEach(function(item){ delete item.age; delete item.gender });
console.log(arraydata);
var arraydata =[
{ id:1, name:"Abraham", age: 20, gender: "male"},
{ id:2, name:"Annie", age: 25, gender: "female"},
{ id:3, name:"Ryan", age: 28, gender: "male"},
{ id:4, name:"Wayne", age: 19, gender: "male"},
{ id:5, name:"Paul", age: 45, gender: "male"}
];
var _ = arraydata.map(function(item) {
return { id: item.id, name: item.name };
});
var jsonData = JSON.stringify(_);
console.log(jsonData);
You can of course chain together the two steps.
Fiddle

Categories

Resources