- Home /
Writing certain values of an array into a different array
I've got an array with multiple numbers in it, and i want to take every 15th value in this array and copy it into a different array.
is that possible(preferably without a loop)?
Answer by CHPedersen · Jul 21, 2011 at 09:28 AM
It's certainly possible, but I don't know how I would do it without a loop, I'm afraid. A loop is the most elegant way traverse arrays.
I would do something like this:
public string[] TakeEvery15th(string[] source)
{
string[] every15th = new string[source.Length / 15];
for (int i = 15, j = 0; i < source.Length; i += 15, j++)
{
every15th[j] = source[i];
}
return every15th;
}
Notice in particular the double counters inside the for-loop. The variable i causes the counter to jump 15 steps at a time in the source array, while the variable j sticks those values in 0, 1, 2... in the destination array.
looking good and logic, could've slapped myself for not doing that.
also, are you sure this is javascript?
I have replaced int[] with string[] to reflect the fact that your numbers are in string format. If you need the strings converted to a number before you return, you can use a parse method, i.e. int.Parse(string) or double.Parse(string), or whatever datatype those numbers are.
This is C#. A translation to javascript should be fairly straight-forward. ;)
translation is going bad, he won't accept the multiple counters in the loop. all the rest is successfully translated
I'm not familiar with Unity's javascript syntax, so it might be that unlike C#, it doesn't support multiple counters inside for-loops. :/ In that case, you might have to take j out of the for-loop declaration, and increment it manually, like this:
int j = 0; for (int i = 15; i < source.Length; i += 15) { every15th[j] = source[i]; j++; }
loop is starting but doesn't fill the every15th array at all...is there any other solution?
Answer by rejj · Jul 21, 2011 at 11:57 AM
Something like this should work if you need it in javascript
// assume "source" exists, and is your original array
// "dest" will be your new array.
var dest = [];
var numItems = Math.floor(source.length / 15);
for (var i = 0; i < numItems; ++i) {
dest.push(source[i * 15]);
}
Array modification is quite expensive, and as-per the C#, not necessary since the array size is calculable in advance.
Your answer
Follow this Question
Related Questions
Simple Array Problem 1 Answer
displaying playerprefs 1 Answer
TextAsset inside the Array - UnityScript/JavaScript 1 Answer
split() for separators more than 1 characters 2 Answers
Increasing And Decreasing An Array Through A Variable 2 Answers