As I know in python i can set a list to a unique list like:
In [12]: a=range(12)
In [13]: a.append(5)
In [14]: a.append(4)
In [15]: a.append(5)
In [16]: a
Out[16]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 5, 4, 5]
In [17]: set(a)
Out[17]: set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
it is very useful for some scene, i just want to know how to this in javascript,
First of all, lists are part of the core Python programming language; arrays are a part of the numerical computing package NumPy. Therefore, you have access to NumPy arrays only if you load the NumPy package using the import command.
Set elements are unique. Duplicate elements are not allowed. A set itself may be modified, but the elements contained in the set must be of an immutable type.
The term "array-like" is used in NumPy, referring to anything that can be passed as first parameter to numpy. array() to create an array (). As per the Numpy document: In general, numerical data arranged in an array-like structure in Python can be converted to arrays through the use of the array() function.
Javascript does not have the notion of sets. However, you can use a side effect of the fact that objects cannot have duplicate property names to replicate the functionality of a set, as seen on this blog article about the topic.
Javascript does not have the notion of sets. However, you can use a side effect of the fact that objects cannot have duplicate property names to replicate the functionality of a set, as seen on this blog article about the topic.
From the article:
var your_array = ['a', 'a', 'a', 'b', 'b'],
set = {};
for (var i = 0; i < your_array.length; i++)
set[your_array[i]] = true;
list = [];
for (var item in set)
list.push(item);
EDIT in 2017: This is no longer true, JS got set support! MDN Docs
empty_set = new Set()
three_element_set = new Set([1, 1, 1, 2, 2, 3])
three_element_set.add(3) // still three element set
No, there isn't. JS is pretty basic, you have to either do it yourself or find a library where someone else has already done it.
The standard way to do this is usually insert elements into a hash, then collect the keys - since keys are guaranteed to be unique. Or, similarly, but preserving order:
function uniq(arr) {
var seen = {}, result = [];
var len = arr.len;
for (var i = 0; i < len; i++) {
var el = arr[i];
if (!seen[el]) {
seen[el] = true;
result.push(el);
}
}
return result;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With