JScript Array with custom array index - javascript

Consider this, I have a JScript array of arrays.
I want to copy a given index of the array into another array using the same index.
So for example:
MyArray = {[0] = Array, [1] = Array, [2] = Array}
I want to copy the 3rd index [2] into another array, such that the first index is not '0' but '2'.
Giving Me:
MyNextArray[2] = {Array}
Apologies for the pseudo code.
Can I make the copy or do I have to first initialize the array and then set a custom index?
Thanks in advance!

MyArray = {[0] = Array, [1] = Array, [2] = Array}
var MyNewArray = sortRay(MyArray, 2);
function sortRay(Ray, firstNr){
MyNextArray = new Array();
MyNextArray[0] = Ray[firstNr];
for(var i = 0, j = 1; i <= Ray.length, i++){
if(i == firstNr){i++, j = 0;}
MyNextArray[i+j] = MyArray[i];
}
return MyNextArray;
}
shld work

Related

Combining 2D Array with Key-Value Array

I have an array where each row is an array that has 2 values, S/N and Description.
array1 = [["xx9","Big Car"],["xx1","Small Car"],["xx9","Big Car"],["xx9"," Big Car"]];
As you can see there are duplicates. So I wrote code that creates a count array that holds the key-value pairs and counts each item. Length of count is 1.
count = [xx1: 1
xx9: 3]
So now I want to combine the two arrays into one new one that includes the quantity, in this example the final output would be as shown below. Note that I have to also remove the duplicates in array1. Order doesn't matter.
final_array = [["1","xx1","Small Car"],["3",xx9","Big Car"]];
Here is my JS code so far but basically the .forEach loops won't work over the count array. Can anyone help me so that this code works on the key-value array.
JS/Jquery:
//Pull the Cart Data & Orangize
var savedList = JSON.parse(localStorage.getItem("partList"));
console.log(savedList);
determineQuantity(savedList); //Count quantity of each item
//Count the Quantity of each item in saved list & create key-value pairs
function determineQuantity(savedList){
var newList = [];
var count = [];
for (var i=0, j = savedList.length; i<j; i++){
count[savedList[i][0]] = (count[savedList[i][0]] || 0) + 1;
};
console.log(count);
//Combine Quantity Array with SavedList Array
count.forEach(function(item,index){
console.log("index = " + index + " item = " + item);
savedList.forEach(function(row){
if ($.inArray(item,row == 0)){ //if found in this row at index 0
var new_part = [count[index],row[0],row[1]];
console.log("new_part = " + new_part);
newList.push(new_part);
};
});
});
console.log(newList);
};
how about this.
var test = function(){
var array = [["xx9","Big Car"],["xx1","Small Car"],["xx9","Big Car"],["xx9"," Big Car"]];
var count = {xx1: 1, xx9: 3};
var map = {};
array.forEach(function(item){map[item[0]] = item[1]});
var newArray = [];
for(var key in count){
if(!map[key])
continue;
newArray.push([count[key], key, map[key]]);
}
console.log(newArray);
}
first of all, you count is a object, not a array. then we dont need forEach

Substr on an array element if not empty

Hei, I have an array containing some empty strings and some strings with content.
I want to slice down the first 5 letters of those which are not empty strings, and put them into a new array. I also want to keep the empty ones.
example:
myArray = [ "","","123456789","","",""];
var newArray = ["","","12345","","",""]
I tried with for loop with if inside if the myArray[i] is empty then don't do substr(), but I get an error that it is not a function.
I actually don't need to put it into a new array, I just want to put the myArray(i).subsrt(5) value into a splice(), but then I get the error:
VM750:82 Uncaught TypeError: Cannot read property 'substr' of undefined
ES6 with array.map
myArray = [ "","","123456789","","",""];
var newArray = myArray.map((s) => s.substr(0, 5))
It's hard to know what your exact problem is without seeing all of your code, but here is a for loop that goes over all the elements in the first array and takes the first 5 or fewer characters of each string to insert into a new array.
myArray = [ "","","123456789","","",""];
var newArray = [];
for(var i = 0; i < myArray.length; i++) {
newArray.push(myArray[i].substr(0,5));
}
exactly what #le_m says:
myArray = [ "","","123456789","","",""];
var newArray = myArray.map(e => e.substr(0, 5));
You need to use substr for non-empty items:
Like this:
myArray = [ "","","123456789","","",""];
for(var i = 0; i < myArray.length; i++) {
temp = myArray[i];
if (temp && temp != "")
myArray[i] = temp.substr(0, 5);
else
myArray[i] = "";
}

Rearranging Elements For Array of Array

I am trying to rearrange elements in an array of arrays but have been unsucessful. Can anyone offer suggestions? Here are two options I have tried. I want to swap/switch places for the first and second elements.
arr1 is an array of arrays (i.e. arr[][]) so I created arr2 to be an updated arr1
var arr2 = [];
for (var n = 0; n <arr1.length; n++){
arr2[n][0] = arr1[n][1];
arr2[n][1] = arr1[n][0];
}
The other thing I tried was:
function order(arr[]){
return [arr[n][1],arr[n][0], arr[n][2], arr[n][3]];
}
var arr2 = order(arr1);
You also need to create a new array for each item:
var arr2 = [];
for(var n = 0; n < arr1.length; n++) {
arr2[n] = [arr1[n][1], arr1[n][0]];
}
it's quite easy:
var a = arr1[n][0];
arr2[n][0] = arr1[n][1];
arr2[n][1] = a;
you need to save the first value as a variable, because if you do as you did(arr2[n][0] = arr1[n][1];), your two array indexes will have the same value.
You did:
a = 1, b = 2;
a = b;
b = a;
Which resolves in a = 2, b = 2
Also, your code as it is now, doesn't work. You need to create a new array for the simulation of multidimensional arrays in javascript.
for(i = 0; i < (yourdesiredamountofarrays); i++)
{
yourarray[i] = new Array();
}
The first example you need to use a temporary variable for the switch:
var arr2 = [];
for (var n = 0; n <arr1.length; n++){
var tempVal = arr1[n][1];
arr2[n][1] = arr1[n][0];
arr2[n][0] = tempArr;
}
The second example, in JS the variable shouldn't have brackets next to it, as it's just a loosely typed variable name.
function order(arr){
return [arr[n][1],arr[n][0], arr[n][2], arr[n][3], arr[n][4]];
}
var arr2 = order(arr1);
Next time, before asking you should check the console. The stackoverflow wiki page on JS has lots of great resources for learning to debug JS.

Generate random display of array elements in an array of arrays?

Ok, i have an array that contains at least two or more arrays that can contain several objects:
array[ [array[n], array[n], array[n], etc...]
my question is how to loop through and randomly pick one object from lets say array[0][1] and randomly pick another object from array[0][15] and produce no duplicates while appending each one to the page.
I have an example of what i am working on here http://jsfiddle.net/I_am_Chris/Yn5Wy/
var randObj1;
var randObj2;
var randArray;
for(i=o; i<array.length; i++){
randArray = array[i]; //get length of "nested" arrays within the array
for(n=0;n<randArray.length; n++){
randObj1 = [][].name
randObj2 = [][].name
}
}
I have tried shuffling the arrays, but that just shuffles the individual arrays, but not the outcome i need.
OK, it sounds like you want N pairs of two choices where each item in the pair is from a different array and you want no repeats.
The no repeats part is going to be efficient and run less risk of infinite looping if you create a parallel data structure that we can remove items from once chosen. This is flatly the simplest way to avoid duplicatesw without having to do a search each time. It also allow you to easily know how many choices are left in any given array in case there are no more possibilities. Here's how you could do that:
function getPairs(origData, N) {
// make copy of the data we can modify to keep track of which choices are used
var copyData = [];
for (var i = 0; i < origData.length; i++) {
copyData.push(origData[i].slice(0));
}
function getRandomValueAndRemove(skipArray) {
var randArray;
// select an array that isn't skipArray
do {
randArray = Math.floor(Math.random() * copyData.length);
} while (randArray === skipArray) ;
// select an item in that array
var randIndex = Math.floor(Math.random() * copyData[randArray].length);
var value = copyData[randArray][randIndex];
// remove that item from copyData
copyData[randArray].splice(randIndex, 1);
// if one of the arrays we selected is now empty, then remove it
if (!copyData[randArray].length) {
copyData.splice(randArray, 1);
// this array is gone so we don't have to worry about selecting it again
randArray = -1;
}
// return data and which array it is
return {value: value, whichArray: randArray};
}
// get N pairs
var pairs = [];
for (i = 0; i < N && copyData.length > 1; i++) {
var item1 = getRandomValueAndRemove();
var item2 = getRandomValueAndRemove(item1.whichArray);
pairs.push([item1.value, item2.value]);
}
// pairs contains an array of pairs
// where each item in a pair is from a different source array
// like this
// [[a, b], [c,d], [e,f]]
return pairs;
}
Working demo: http://jsfiddle.net/jfriend00/sy6XF/
If the pairs can contain any two objects, then it's simpler to do it like this.
You have some data that looks like this (array of arrays):
var origData = [[...], [...], [...]];
You can create a temporary single flat array with all the objects in it. Generate one random number to get an object. Then, remove that object from the temporary array and repeat the process (with a now shorter array). This is the simplest way of avoiding duplicates because you remove the ones you've used from the temporary array and select random choices from the remaining elements.
Here's a code example for the second option:
var origData = [[...], [...], [...]];
var flatData = [];
var item;
// put everything into flatData
for (var i = 0; i < origData.length; i++) {
flatData.push.apply(flatData, origData[i]);
}
var pairs = [];
// now select N random pairs
for (var i = 0; i < N && flatData.length > 1; i++) {
var rand = Math.floor(Math.random() * flatData.length));
var obj1 = flatData[rand];
// now remove that element from flatData so we won't pick it again
flatData.splice(rand, 1);
// get second randome value
rand = Math.floor(Math.random() * flatData.length));
var obj2 = flatData[rand];
pairs.push([obj1, obj2]);
}
// pairs contains an array of pairs
[[a, b], [c,d], [e,f]]
to generate a random number, use Math.random()
Math.random() generates a random number between 0 and 1. Then multiply by the length of the nested array to generate an index for the element you want from the nested array. Repeat the random number generation for the second index as long as it's equal to the first index. Store the results in the results array.
var results = [];
var genRandNum = function(max) {
return Math.random() * (max - 1);
}
for(var i = 0; i < array.length; i++) {
var nestedArray = array[i];
var randIndex1 = genRandNum(nestedArray.length);
results.push(nestedArray[randIndex1]);
do {
var randIndex2 = genRandNum(nestedArray.length);
} while (randIndex1 === randIndex2);
results.push(nestedArray[randIndex2]);
return results;
}
FYI, didn't test this because it wasn't clear what your test should produce.

One dimensional to two dimensional array javascript

First I have an array like:
arr = [[r,g,b,a],[r,g,b,a],[r,g,b,a],[r,g,b,a],[r,g,b,a],[r,g,b,a]]
I can 'flatten' it using
arr = Array.prototype.concat.apply([],arr)
or using a for-next loop and push.apply
Then I got:
[r,g,b,a,r,g,b,a,r,g,b,a,r,g,b,a,r,g,b,a]
How do I get it back to its original format as easy as possible?
var newArr = [];
while(arr.length){
newArr.push(arr.splice(0,4));
}
Something like this, perhaps:
var old = [];
for (var index = 0; index < arr.length; index+= 4)
old.push( arr.slice(index, index + 4) );

Categories