How to Merge Subarray Values and Remove Duplicates

How to merge subarray values and generate a 1-dimensional array of unique values?

In your desired output indexes are same, you never achieve that. because same indexes are over-written by most recent values.

You can get like below:-

$final_array = array_unique(call_user_func_array('array_merge', $array)); //convert multi-dimensional array to single dimensional and remove duplicates
asort($final_array); // sort by value. this is optional
$final_array = array_values($final_array); // re-index final array and this is optional too
echo "<pre/>";print_r($final_array); // print final array

Output:- https://eval.in/752750

Merge subarrays into single one and remove duplicates if they have same id using ruby on rails

array.group_by(&:first).map do |id, records|
names = records.map(&:second).join(', ')
values = records.map(&:last).join(', ')

[id, names, values]
end

As you asked the reversed question recently, I suggest you to read the Enumerable, Array, Hash and String documentations. It will give you an instant boost in expressiveness and understanding of how to do common tasks with Ruby.

How to efficiently combine all subarrays with related id's and remove all duplicate objects

Consider using of union-find algorithm based on disjoint-sets data structure.

Code is very simple, wiki pseudocode is close to real one.

You have to walk through all element pairs (in longer lists it's enough to get neighbor pairs), after that every element will point onto its parent (set representative element).

How to remove duplicate values from a multi-dimensional array in PHP

Here is another way. No intermediate variables are saved.

We used this to de-duplicate results from a variety of overlapping queries.

$input = array_map("unserialize", array_unique(array_map("serialize", $input)));

merge duplicate objects in an array and combine sub array of each object

I think, reduce() would do the job:

const accounts = [{"Id":103,"accountList":[{}]},{"Id":103,"accountList":[{"tokenId":"5aasdasdsdnjn3434nadd","featureId":2840}]},{"Id":112,"accountList":[{"tokenId":"5d30775bef4a722c38aefaaa","featureId":2877}]},{"Id":112,"accountList":[{"tokenId":"5d30775bef4a722c38aefccc","featureId":2856}]}];

const result = [...accounts
.reduce((r, o) => {
const record = r.get(o.Id)||{}
r.set(o.Id, {
Id: o.Id,
accountList: [
...(record.accountList||[]),
...o.accountList.filter(o =>
Object.keys(o).length != 0)
]
})
return r
}, new Map())
.values()]

console.log(result);
.as-console-wrapper {min-height: 100%}

JavaScript - merge two arrays of objects and de-duplicate based on property value

Using a double for loop and splice you can do it like so:

for(var i = 0, l = origArr.length; i < l; i++) {
for(var j = 0, ll = updatingArr.length; j < ll; j++) {
if(origArr[i].name === updatingArr[j].name) {
origArr.splice(i, 1, updatingArr[j]);
break;
}
}
}

Example here



Related Topics



Leave a reply



Submit