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

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>');

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%}

Drop all duplicates from array using JavaScript [duplicate]

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)

Creating dictionary using python from javascript var data [duplicate]

This question already has answers here:
Convert [key1,val1,key2,val2] to a dict?
(12 answers)
Make dictionary from list with python [duplicate]
(5 answers)
Convert list into a dictionary [duplicate]
(4 answers)
Closed 4 years ago.
trying to figure out how to do this and have yet to find a good solution. I pulled this data out of an XML response. It was in a var tag. Now what I would like to do is create a dictionary out of it. The domain.com should be paired with the number right listed behind it.
This is the data:
[
'cb131.domain1.com', '147827',
'cb143.domain2.com', '147825',
'cb175.domain1.com', '147454',
'cb190.domain.com', '146210',
'cb201.domain.com', '146208',
'cb219.domain.com', '146042',
'cb225.domain.com', '146282',
'cb900.domain.com', '148461',
'cb901.domain.com', '148493',
'cb902.domain.com', '148495',
'cb903.domain.com', '148497',
'cb904.domain.com','148499',
'cb905.domain.com', '148501',
'cb906.domain.com', '148503',
'cb907.domain.com', '148505',
'cb908.domain.com', '148507',
'cb909.domain.com', '148509'
]
So for example cb131.domain1.com should be paired with 147827, cb143.domain2.com paired with 147825 and so on.
Drawing a blank on a good quick solution on how to do this. Hopefully someone can help.
Thanks!
Edited with answer I choose below:
I choose this answer and also to help anyone else I add a nice way to print out the results (data is the string I obtained):
import ast
i = iter(ast.literal_eval(data))
dic = dict(zip(i, i))
for key , value in dic.items():
print(key, " :: ", value)
This should do it. Assuming the list is saved to a variable l:
keys = l[::2]
vals = l[1::2]
dic = dict(zip(keys, vals))
You can create an iterator from the list after using ast.literal_eval to parse it from the input text, zip the iterator with itself, and pass the generated sequence of tuples to the dict constructor:
import ast
i = iter(ast.literal_eval(data))
dict(zip(i, i))
Assuming you have the above in a python array called data, you can do:
new_data = []
for i in range(0, len(data), 2):
new_data.append((data[i], data[i+1]))
Now new_data would be a list of tuples. You could certainly create a better data structure to hold these pairs if you want.
I do not yet know Python that I can write a snippet, but:
initialize an empty dictionary in Python
create a for loop counting index from 0 to length of your array in steps of two.
inside add a dictionary entry with key of value at index and value at index + 1
perhaps check for duplicates
Does this answer help you?
This is Python - quickly google'd:
dictionary = { }
for idx in range(0, len(data), 2)
dictionary[data[idx]] = data[idx + 1]

Transform values in JavaScript array to values in an array [duplicate]

This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 5 years ago.
Let's say I have the following Object.
const result = [{date:'2016-11-21',name:'Bob',score:0.1034947}{date:'2016-10-21',name:'Bill',score:0.2081911},{date:'2016-10-21',name:'Mary',score:0.234947},{date:'2016-10-21',name:'Bob',score:0.1034947},{date:'2016-11-21',name:'Bill',score:0.2081911},{date:'2016-11-21',name:'Mary',score:0.234947},{date:'2016-12-21',name:'Bob',score:0.1034947},{date:'2016-12-21',name:'Bill',score:0.2081911},{date:'2016-12-21',name:'Mary',score:0.234947}];
What I want to take that object and turn those values and put them in separate arrays. So for example,
dateArray = ['2016-11-21','2016-10-21', ....]
I am really quite new to JavaScript. I am trying to do it with map but not sure if I am on the right track. So thanks in advance!
var dateArray = [];
for (var index in result) {
var item = result[index];
dateArray.push(item.date);
}
You can use Array.prototype.map to transform your array to a new one by projecting every original value with the defined function.
var dateArray = result.map(function(r) {
return r.date;
});
This code literally means "take array result and make a new array dateArray of the same length where every item is a value of date property of corresponding item of result".
You can also use arrow-function, but it is only compatible with ECMAScript 6.
var dateArray = result.map(r => r.date);

Categories