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
Related
I have this bunch of code
var rows = document.querySelectorAll('.workRow')
var codes = []
for(var i=0;i<rows.length;i++){
var timeCodesInputs = rows[i].getElementsByClassName('xCell')
for(var j=0;j<timeCodesInputs.length;j++){
if(timeCodesInputs[j].innerHTML == "x"){
codes.push(timeCodesInputs[j].dataset.dataHour)
}
}
}
it works ok but it pushed everything to one array. What I want to get an array of arrays where one array if the data from one row. How to do it?
Ciao, try to push row data in one array and then push this array into codes array like:
var rows = document.querySelectorAll('.workRow')
var codes = []
for(var i=0;i<rows.length;i++){
var rowArray = [];
var timeCodesInputs = rows[i].getElementsByClassName('xCell')
for (var j=0;j<timeCodesInputs.length;j++){
if(timeCodesInputs[j].innerHTML == "x"){
rowArray.push(timeCodesInputs[j].dataset.dataHour)
}
}
codes.push(rowArray)
}
Update: The answer to this question is bellow. Thanks to dougtesting on a different thread. add array together, display sum
function hello() {
var arr = [];
for (var i = 0; i < 10; i++) {
arr.push(prompt('Enter number' + (i+1)));
}
var total = 0;
for(i=0; i<arr.length; i++) {
var number = parseInt(arr[i], 10);
total += number;
}
console.log(total);
}
//End of answer.
I am trying to have a user input 10 numbers. Then add those numbers together and display the output to the user. I was able to get the amount of inputs (10) into a array but I can't get arrays contents. I feel like I'm missing something simple. Would you mind taking a look?
// https://stackoverflow.com/questions/28252888/javascript-how-to-save-prompt-input-into-array
var arr = []; // define our array
for (var i = 0; i < 10; i++) { // loop 10 times
arr.push(prompt('Enter number' + (i+1))); // push the value into the array
}
alert('Full array: ' + arr.join(', ')); // alert the result
var arrEquals = []; //Empty Arr
arrEquals = arr.push(); //turn string into var
alert (arrEquals);//show string to admin for debug
//(for loop) console out # of array elements. does not output what is in array
//this is half the battle
for (var a = 0; a < arrEquals; a++){
var a = Number(a); //ensure input is Number()
console.log(a + "A"); //used for debug
}
//taks sums in array and adds them together
//this is the other half of the problem
// https://www.w3schools.com/jsref/jsref_forEach.asp
// var sum = 0;
// var numbers = [65, 44, 12, 4];
// function myFunction(item) {
// sum += item;
// demo.innerHTML = sum;
// }
This is probably one of the simplest examples of something that Javascript's built in array .reduce() function would be used for. Effectively, you're "reducing an array to a single value".
A reduce works by taking an array and running a function on each item. This "callback" function receives the value that the previous function returns, processes it in some way, then returns a new value. Worth noting, the reduce function also takes a 2nd argument that acts as the initial value that will be passed to the callback function the first time.
array.reduce(callbackFunction, initialValue);
Here's an example of reduce being used to sum an array.
var result = [1,2,3,4,5,6,7,8,9,10].reduce(function(accumulator, currentValue) {
return accumulator + currentValue;
}, 0); // start with an initial value of 0
console.log(result);
Using ES6 syntax, this can be further simplified to a one-liner
var result = [1,2,3,4,5,6,7,8,9,10].reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(result);
In your loop you're referencing arrEquals like for (var a = 0; a < arrEquals; a++){. you need to reference it like for (var a = 0; a < arrEquals.length; a++){ because just referencing the array doesn't tell javascript how long it is, or what number to count to. the .length returns a number, that number is how many items are in the array.
var arr = []; // define our array
for (var i = 0; i < 10; i++) { // loop 10 times
arr.push(prompt('Enter number' + (i+1))); // push the value into the array
}
arr = arr.join(', ');
alert('Full array: ' + arr); // alert the result
var arrEquals = []; //Empty array
arrEquals.push(arr); //assign arr string to an empty array
alert (arrEquals[0]); //show array[0] string to admin for debug
Is this what you are looking for? You need to put the arr.join() result to a variable, like itself.
You shouldnt be using arr.push() at all if you're not pushing new array items on it
//(for loop) console out # of array elements. does not output what is in array
//this is half the battle
for (var a = 0; a < arrEquals.length; a++){
//a is always a int in this case
console.log(a + "A"); //used for debug
}
I searched a lot, but I could not get a satisfactory answer on the net. In javascript, how do I add an array into another multidimensional array at a particular position based on a key value?
finalArray = []; //final result to be stored here
for(var i=0; i<5; ++i)
{
var temp = [];
for(var j in $scope.team[i])
{
// counter = some value calculated here
temp[j] = $scope.team[i][j][counter];
}
finalArray[group[i]] = temp; // This gives an error
}
basically, I have
group = [ 'alpha' ,'beta', 'gamma' ]; //this array generated dynamically
my finalArray should be like,
finalArray['alpha'] = [ some records ];
finalArray['beta'] = [ some records ];
....
As far as I know, the way to add array into another array is to use .push() method, but that creates indices as 0, 1, 2... which is not desired. Please help me out
You have to use Object instead of Array. Make the following changes in the code
finalArray = {}; //final result to be stored here
for(var i=0; i<5; ++i)
{
var temp = {};
for(var j in $scope.team[i])
{
// counter = some value calculated here
temp[j] = $scope.team[i][j][counter];
}
finalArray[group[i]] = temp;
}
console.log(finalArray); //to see the object key value structure
now you can reference the values in finalArray with group[i] name. Hope this helps
You have to define your finalArray variable as Object instead of and Array:
var finalArray = {}; //or better in your case finalMap
var group = [ 'alpha' ,'beta', 'gamma' ];
var finalArray = {}; //declare it object as you dont want 0,1 indexes
for (var index in group){
finalArray[group[index]] = "some records/arry of records"
}
console.log(finalArray);
DEMO
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.
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