Drop all duplicates from array using JavaScript [duplicate] - javascript

This question already has answers here:
remove all elements that occur more than once from array [duplicate]
(5 answers)
How to remove all duplicates from an array of objects?
(77 answers)
Completely removing duplicate items from an array
(11 answers)
Closed 1 year ago.
I have an array of objects with input like below
var jsonArray1 = [{id:'1',name:'John'},{id:'2',name:'Smith'},{id:'3',name:'Adam'},{id:'1',name:'John'}]
The id 1 appears twice and I would like to drop all duplicate records .i.e. my output should look like
[{id:'2',name:'Smith'},{id:'3',name:'Adam'}]
Can you please guide/direct me in how I can drop all duplicate records

Create Map from an array where key of the Map is your desired id, duplicated won't be preserved (only last occurrence will). After just take the values from Map.
Removing all of occurrences of duplicates (this is what OP wanted):
const input = [{id:'1',name:'John'},
{id:'2',name:'Smith'},
{id:'3',name:'Adam'},
{id:'1',name:'John'}]
const res = input.filter((x, i, arr) =>
arr.filter(e => e.id === x.id).length === 1)
console.log(res)
Preserving 1 occurrence of duplicates:
const input = [{id:'1',name:'John'},
{id:'2',name:'Smith'},
{id:'3',name:'Adam'},
{id:'1',name:'John'}]
const unique = [...new Map(input.map(item => [item.id, item])).values()]
console.log(unique)

Related

Best way to sort array based of different sets of data? [duplicate]

This question already has answers here:
Javascript sort array of objects using array of priority
(2 answers)
Closed 1 year ago.
var array = [{value:"13",type:"Fruit"},{value:"61",type:"Animal"},
{value:"19",type:"Fruit"},{value:"71",type:"Animal"},
{value:"12",type:"Fruit"},{value:"15",type:"Fruit"},
{value:"11",type:"Plant"},{value:"10",type:"Fruit"},
{value:"16",type:"Plant"}]
What is the best/optimized way to sort this array such that I get all elements of type Fruit first and then the elements of type Animal (by picking elements from end of array).
expectedOutput = [{value:"10",type:"Fruit"},
{value:"15",type:"Fruit"},{value:"12",type:"Fruits"},
{value:"19",type:"Fruit"},{value:"13",type:"Fruit"},
{value:"71",type:"Animal"},{value:"61",type:"Animal"},
{value:"16",type:"Plant"},{value:"11",type:"Plant"}]
Note:- I don't need to sort it Alphabetically. It must be sort depending upon the specific type.
You can store the order of the type properties in an array, then subtract the index of the type property when sorting to determine precedence:
const order = ["Fruits", "Animal"]
var array = [{value:"13",type:"Fruit"},{value:"61",type:"Animal"},
{value:"19",type:"Fruit"},{value:"71",type:"Animal"},
{value:"12",type:"Fruit"},{value:"15",type:"Fruit"}]
const sorted = array.sort((a,b) => order.indexOf(a.type) - order.indexOf(b.type))
console.log(sorted)

How can I remove all duplicated elements in an array (including first occurrence) [duplicate]

This question already has answers here:
Get all unique values in a JavaScript array (remove duplicates)
(91 answers)
Merge sorted arrays and remove duplicates javascript
(5 answers)
Closed 1 year ago.
This post was edited and submitted for review 1 year ago and failed to reopen the post:
Original close reason(s) were not resolved
I was studying JS in CodeWars and I didn't find a method to remove all duplicated elements in an array. I need to do exactly this:
a = [1,2,2,2,3,4,5,6,6,7]
b = [1,2,7,8,9]
Return a unique array = [3,4,5,8,9]
delete all the duplicated items, including the first occurrence
How can I do this? I already use for, if, forEach, but no success.
You may simply
count the occurences of each element (to preserve the original element types, you may apply Array.prototype.reduce() together with Map against merged array)
then, filter out those that are seen more than once:
const a = [1,2,2,2,3,4,5,6,6,7],
b = [1,2,7,8,9],
uniques = [
...[...a, ...b]
.reduce((acc,item) =>
(acc.set(item, (acc.get(item)||0)+1), acc), new Map)
.entries()
].reduce((acc, [key, value]) =>
(value === 1 && acc.push(key), acc), [])
console.log(uniques)
.as-console-wrapper {min-height:100%}

How can i compare and concat two arrays on ReactJS [duplicate]

This question already has answers here:
remove common elements of two arrays in jquery
(4 answers)
Closed 3 years ago.
Lets say i had two arrays
a.["mark#example.com", "bob#example.com"]
b.["carl#example.com", "mark#example.com", "bob#example.com", "josh#example.com"]
How can i make a third array, using the variables that are present in the second one, but not on the first one?
the desired output should be this:
c.["carl#example.com", "josh#example.com"]
const arrayA = ["mark#example.com", "bob#example.com"]
const arrayB = ["carl#example.com", "mark#example.com", "bob#example.com", "josh#example.com"]
const arrayC = arrayB.filter(x => !arrayA.includes(x))
console.log(arrayC)

Getting the Key of a Key Value Pair [duplicate]

This question already has answers here:
How to get a key in a JavaScript object by its value?
(31 answers)
Closed 4 years ago.
I have a key value pair array in js
var tabList = {0:'#description', 1:'#media', 2:'#attributes', 3:'#calendar', 4:'#pricing'}
I'm using the keys to get the values in my code
ie. tabList[2] returns #attributes
I thought I could do the same in reverse to get the key
tabList[#media] and have it return 1
But this doesn't work
How can I fetch the key with only the value as input?
There are plenty of solutions here Swap key with value JSON
I will flip key with values 1st
var tabList = {0:'#description', 1:'#media', 2:'#attributes', 3:'#calendar', 4:'#pricing'}
let flipped=Object.assign({}, ...Object.entries(tabList).map(([k,v]) => ({ [v]: k })))
console.log(flipped);
console.log(flipped['#description']);

Ordering of array values to match another array ES6 [duplicate]

This question already has answers here:
Javascript custom sort algorithm according to another array
(4 answers)
Closed 6 years ago.
In a nutshell, what I'm trying to do is use the order of one array to follow the order of another...
For example... (Using ES6 React)
const orderArr = ["Daniel","Lucas","Gwen","Henry","Jasper"];
const nameArr = ["Gwen","Jasper","Daniel"];
to return
Daniel // first
Gwen // second
Jasper // third
so the new array would look like const newNameArr = ["Daniel","Gwen","Jasper"]; // following the order
orderArr is the ordered array I'd like to follow. So if any other arrays come about (nameArr) they should follow the order of orderArr.
Is this even possible?
One way would be to filter out the ones that don't appear in both arrays, using orderArr as the base. This ensures they'll appear in the same order as they appear in orderArr.
const orderArr = ["Daniel","Lucas","Gwen","Henry","Jasper"];
const nameArr = ["Gwen","Jasper","Daniel"];
const newNameArr = orderArr.filter((x) => nameArr.indexOf(x) > -1);
document.write('<pre>' + JSON.stringify(newNameArr, null, 2) + '</pre>');

Categories