- Home /
Obtaining a Array with Unique Items
Hello. I want a array with unique items. For example, {1, 2, 2, 3, ,4 ,4, 4} => {1, 2, 3, 4} I found looking good javascript, but it doesn't work in unity script. And I'm not able to modify it. Could help me to modify this script?
function unique(array) {
var storage = {};
var uniqueArray = [];
var i,value;
for ( i=0; i<array.length; i++) {
value = array[i];
if (!(value in storage)) {
storage[value] = true;
uniqueArray.push(value);
}
}
return uniqueArray;
}
Can you use LINQ from Javascript? If so, you can just do array.Distinct()
Oh, LINQ looks simple! But I can't understand how to use it although I studied it. Could you tell me more detail about it?
You simple need to add the reference at the top, probably
import System.Linq;
and then you can use:
var res = array.Distinct();
now your res has no duplicate.
For more on Linq in Unity you can look there:
http://unitygems.com/linq-1-time-linq/
but it is in C#
I would recommend mastering many more basic program$$anonymous$$g concepts first before using LINQ or finding tools because no matter how easy something is to use, you'll still never understand how to use it. Program$$anonymous$$g takes time and endless learning, if you're not up for it, you probably should consider something that interests you more.
Answer by SinisterRainbow · Jun 27, 2013 at 03:28 AM
This only is guaranteed to work when your original array is sorted (as in your example):
var lastValue = Mathf.Infinity;
for (i=0; i < array.length; ++i) {
if (array[i] != lastValue) {
uniqueArray.push(array[i]);
lastValue = array[i];
}
}
I don't know Javascript well so I'm just copying your syntax, but the logic is sound (when sorted).. lastvalue remembers the last unique value from the original array, and so only uniques get placed in the new one. (Edit note: this is only partial code, i didn't copy all of the code from your example in case you are new to programming, i just did the important part)
Your answer
Follow this Question
Related Questions
Shotgun using array/list in Javascript 1 Answer
Convert Array into One String (Js) 1 Answer
Help me Convert JS to C# 2 Answers
Reading and Storing External Data into Memory (From Text) 1 Answer