Get grouped array which has same value from array using lodash [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have an array like this.
[{id: 1, name: "john", item:['a']},
{id: 1, name: "john", item:['b']},
{id: 2, name: "linda", item:['c']},
{id: 2, name: "linda", item:['d']},
{id: 3, name: "liam", item:['e']}
]
I hope to get grouped arrays having same id and name value like this
[{id: 1, name: "john", item:['a']},
{id: 1, name: "john", item:['b']}
],
[{id: 2, name: "linda", item:['c']},
{id: 2, name: "linda", item:['d']}
],
[{id: 3, name: "liam", item:['e']}
]
Please help me

One solution could be to store the items in a map (for simplicity an object) based on the id and then get the values from that object.
First, we have to check if we already have values stored for that id if that is the case we push the value to the array, if no we have to create the array.
const objMap = {};
items.forEach(item => {
const {id} = item;
if(objMap[id]) objMap[id].push(item);
else objMap[id] = [item];
})
const groupedValues = Object.values(objMap)
I hope that this solves your problem.

Related

What is the best way add all array item in Javascript [duplicate]

This question already has answers here:
Merge/flatten an array of arrays
(84 answers)
Closed 1 year ago.
const arr1 = [
[{ id: 1 }],
[{ id: 2 },{ id: 3 }],
[{ id: 4 }]
];
I want to add all items in this array how can I do this. I want my output as Like:
const arr2 = [
{id:1},
{id:2},
{id:3},
{id:4}
]
Using arr1.flat() will work for your example. If you have an array of even greater depth of nested arrays of objects, you can even use arr1.flat(Infinity) to flatten to a variable depth:
const arr1 = [
{ id: 0 },
[{ id: 1 }],
[{ id: 2 },{ id: 3 }],
[{ id: 4 }]
];
console.log(arr1.flat());

How to sync the indices of two arrays based on a shared value in Javascript? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Given two arrays of the same length and identical content, how can one sort an array to be the in same order as the second array, based on a shared property?
Example:
let array1 = [{id: 123, ...}, {id: 456, ...}, {id: 789, ...}] // order always stays the same
let array2 = [{id: 456, ...}, {id: 789, ...}, {id: 123, ...}] // order is always different
How can I sort array1 such that:
array1[0].id is 456 and
array2[0].id is 456
Loop through the first and push to the second by index:
let arr1 = [{id: 123}, {id: 456}, {id: 789}] // order always stays the same
let arr2 = [{id: 456}, {id: 789}, {id: 123}]
arr1.forEach((obj1, idx) => {
arr2[idx] = obj1
})
console.log(arr1, arr2)
Assuming array2 has the objects we care about and array1 specifies the order, map over the ordering array using it to select the objects to be ordered...
let array1 = [{id: 123 }, {id: 456 }, {id: 789, }]
let array2 = [{id: 456, name: '456' }, {id: 789, name: '789' }, {id: 123, name: '123' }]
let array2ElementsSortedByArray1 = array1.map(e => {
return array2.find(e2 => e2.id === e.id)
})
console.log(array2ElementsSortedByArray1)
You can create a hash of the shape {id: index, ...} from array2 and then use this to order the elements of array1. This saves you the cost of find() on each iteration.
let array1 = [{ id: 123, }, { id: 456, }, { id: 789, }] // order always stays the same
let array2 = [{ id: 456, }, { id: 789, }, { id: 123, }]
const
indeces = Object.fromEntries(array2.map(({ id }, i) => [id, i])), // { 456: 0, 789: 1, 123: 2 }
ordered = [];
array1.forEach(o => ordered[indeces[o.id]] = { ...o });
console.log(ordered)

Unique objects from array based on two properties javascript [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
lets say we have an array of objects:
results = [
{id: 1, name: John},
{id: 2, name: Gabo},
{id: 1, name: Anna},
{id: 3, name: Gabo}
{id: 1, name: Jack}, ]
I want function which gets all this objects which has unique id and name and it's value is not in other object.
results = [
{id: 1, name: John}, // unique id-name so we add to array
{id: 2, name: Gabo}, // unique id-name so we add to array
{id: 1, name: Anna}, // name is unique but object with this id already exists in array so we reject
{id: 3, name: Gabo} // id is unique but object with this name already exists in array so we reject
{id: 1, name: Jack}, ] //etc..
results = [
{id: 1, name: John},
{id: 2, name: Gabo},
You can use Set to register and then quickly check for duplicate id or name:
function getUniq(items) {
const ids = new Set();
const names = new Set();
return items.filter((item) => {
if (ids.has(item.id) || names.has(item.name)) {
return false;
}
ids.add(item.id);
names.add(item.name);
return true;
});
}

How to implement complex arrays? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
For example, when id is equal to 1, an array is ['a', 'b'], and when id is equal to 2, another array is ['c']. The result of these two arrays is [["a","b "],["c"]]
I want the results as follows:
[["a","b"],["c"]]
my code:
var data = [{
id: 1,
name: 'a'
},
{
id: 1,
name: 'b'
},
{
id: 2,
name: 'c'
}
]
Using reduce:
var data = [{
id: 1,
name: 'a'
},
{
id: 1,
name: 'b'
},
{
id: 2,
name: 'c'
}
]
let result = data.reduce((acc, item) => {
return item.id === 1 ? acc[0].push(item.name) : acc[1].push(item.name), acc
},[[], []])
console.log(result)

JavaScript/React - Update a value in array with particular key name from a array of arrays [duplicate]

This question already has answers here:
Find object by id in an array of JavaScript objects
(36 answers)
Closed 5 years ago.
In the below array of arrays I need to update the id value for a particular name.
objArray = [{ name: John, id: 12}, { name: Jake, id: 45}, { name: Jacob, id: 78}];
Ex: If user enters a name and id in text boxes and clicks submit I want to update the id in the array for the particular name.
I can accomplish this using for loops but can you please let me know the most efficient way to do this in Java Script/React?
Use the find function and set the entered name.
Look at this code snippet
let objArray = [{ name: "John", id: 12}, { name: "Jake", id: 45}, { name: "Jacob", id: 78}];
let name = 'Jake'
let newId = 59;
objArray.find((o) => o.name === name).id = newId;
console.log(objArray);
.as-console-wrapper {
max-height: 100% !important
}
You can use findIndex to get the index of the object whose name matches. Then use that index to update the id
var objArray = [{
name: 'John',
id: 12
}, {
name: 'Jake',
id: 45
}, {
name: 'Jacob',
id: 78
}];
function update() {
var getVal = document.getElementById('ip').value.trim();
var getIndex = objArray.findIndex(function(item) {
return item.name.toLowerCase() === getVal.toLowerCase();
})
objArray[getIndex].id= "newId"
console.log(objArray)
}
<input type="text" id="ip">
<button onclick="update()">Update</button>

Categories