I have a table 10 rows, 10 columns. I want to define an array where I can place a value at e.g. pos. row 5, column 3.
The value itself is an array with more entries. And the entry of this array is also an array.
Example:
Row 1, column 1:
My text 1, Link to text 1
My text 2, Link to text 2
Row 4, column 5:
My text 3, Link to text 3
Row 6, column 2:
My text 1, Link to text 1
My text 2, Link to text 2
My text 3, Link to text 3
My text 4, Link to text 4
Not every table entry needs to be defined. A table element entry can have multiple entries. An entry consists of two values. A text and the link for the text.
The html-table is already defined. Now I want to fill it with the values (links) above.
My problem is, how to create an efficient data structure so that I easily can find table-positions that have entries (maybe without looping 10 rows 10 columns). For each entry I want to get the list of texts + links.
And how to access/read each entry of my definition. (I have no problem placing the value to my html-table.)
I'd really appreciate if someone could give me some code-example how to set up such a data structure.
var multiArray = [ ['element 0, 0', 'element 0, 1', 'element 0, 2'], ['element 1, 0', 'element 1, 1']];
and so on...
EDIT
every single notation in [] is an array, so you just have to combine them into an another array
Just use an array of array if the memory is not the problem;
var table = [];
table.length = 10; // 10 rows;
for (var i = 0; i < array.length; i++) {
table[i] = [];
table[i].length = 20; // 20 columns for each row.
}
If the table is big but only a few cells are used, you can also use a hash of hash:
var table = {};
table.rowCount = 10; // there're 10 rows
table[1] = {}
table[1].columnCount = 20 // 20 cells for row 1
table[1][3] = "hello world";
// visit all cells
for (var row in table) {
for (var column in table[row] {
console.log(table[row][column]);
}
}
You can even mix hash and array.
You could create a simple wrapper to make calling convenient: http://jsfiddle.net/QRRXG/2/.
A multidimensional array is just an array in another. So you can build an array with 10 arrays which in turn have 10 arrays in each. Then get one with arr[i][j].
Items can be represented as an object:
{ name: "foo", link: "bar" }
then such an item can be parsed like obj.name and obj.link.
var multi = (function() {
var data = [];
// initialize
for(var i = 0; i < 10; i++) {
data[i] = [];
for(var j = 0; j < 10; j++) {
data[i][j] = [];
}
}
return {
get: function(i, j) { // will return an array of items
return data[i][j];
},
push: function(i, j, v) { // will add an item
data[i][j].push(v);
},
clear: function(i, j) { // will remove all items
data[i][j] = [];
},
iterateDefined: function(f) {
for(var i = 0; i < 10; i++) {
for(var j = 0; j < 10; j++) {
if(data[i][j].length > 0) {
f(data[i][j], i, j);
}
}
}
}
};
})();
You can the use it like:
multi.push(2, 3, { name: "foo", link: "test1" });
multi.push(2, 3, { name: "bar", link: "test2" });
multi.push(1, 4, { name: "haz", link: "test3" });
multi.push(5, 7, { name: "baz", link: "test4" });
multi.clear(5, 7);
console.log(multi.get(2, 3)); // logs an array of 2 items
console.log(multi.get(1, 4)); // logs an array of 1 item
console.log(multi.get(5, 7)); // logs an array of 0 items
console.log(multi.get(2, 3)[0].name); // logs "foo"
console.log(multi.get(2, 3)[1].link); // logs "test2"
multi.iterateDefined(function(items, i, j) {
console.log(items, i, j); // will log two times
});
Create a utility Object:
var DataTable = {
source: [],
setEntry: function(i,j,e) {
var o ;
if( !!! ( o = this.source[i] ) ) o = this.source[i] = [] ;
o[j] = e ;
return this ;
},
getEntry: function(i,j) {
var o, e = null ;
if( !! ( o = this.source[i] ) ) e = o[j] || null ;
return e ;
}
} ;
The other answers seem to suggest placing dummy Arrays as placeholders for coordinates that are unused. This -- while it is not wrong -- is unnecessary: if you set an entry on an Array in JavaScript whose index exceeds the current range the Array is essentially padded with undefined values.
var a = [ ] ; // a length is 0
a[1024] = 1 // a length is now 1025, a[1] is undefined
Then add the values you require:
DataTable.setEntry( 1, 1, ["My text 1","Link to text 1","My text 2","Link to text 2"] )
.setEntry( 4, 5, ["My text 3","Link to text 3"] )
//..
;
The following control statements will return the value of the Arrays of the coordinates or null (if DataTable.source does not contain a nested Array for the given coordinates):
console.log("(!!) d.source: " + DataTable.getEntry(4,5) ) ;
console.log("(!!) d.source: " + DataTable.getEntry(1,1) ) ;
console.log("(!!) d.source: " + DataTable.getEntry(0,0) ) ;
Try it here:
link to JSFiddle
UPDATE:
This is a pretty old post, but since I received a comment to explain the snippet, here's an update with class syntax and a few more comments:
class DataTable {
data = [];
constructor() {
// bind methods to this instance
this.setEntry = this.setEntry.bind(this);
this.getEntry = this.getEntry.bind(this);
}
// set an entry at the given coordinates (row and column index pair)
setEntry(rowIndex, columnIndex, value) {
let row = this.data[rowIndex];
// create the row lazily if it does not exist yet
if(typeof row === 'undefined') {
this.data[rowIndex] = [];
row = this.data[rowIndex];
}
// set the value
row[columnIndex] = value;
}
// get the entry at the given coordinates (row and column index pair)
getEntry(rowIndex, columnIndex) {
const row = this.data[rowIndex];
// test if the row is defined; if not return null.
if(typeof row === 'undefined') { return null; }
else {
// return the value or fall back to null
return row[columnIndex] || null;
}
}
}
const d = new DataTable();
d.setEntry(1, 1, ["My text 1","Link to text 1","My text 2","Link to text 2"]);
d.setEntry(4, 5, ["My text 3","Link to text 3"]);
console.log(`d.getEntry(4, 5) = ${d.getEntry(4, 5)}`);
console.log(`d.getEntry(1, 1) = ${d.getEntry(1, 1)}`);
console.log(`d.getEntry(0, 0) = ${d.getEntry(0, 0)}`);
Related
I am trying to find 3 or more matching items in array but it is only matching the first 3 and none matching for the rest of the array. If anyone could help would be great :)
var grid = [2,2,2,5,5,5,3,3,3,3];
checkResults();
function checkResults(){
var list_matches = []; // store all matches found
var listcurrent = []; // store current
var maxitems = 3;
var last = -1; // last cell
for(let j =0; j < grid.length; ++j){
let item = grid[j];
// check if last is null
if(last == -1){
// add first item
listcurrent.push(item);
last = item;
console.log("Added: "+item);
continue;
}
let wasMatch = false;
// check match
if(item == last){
wasMatch = true;
listcurrent.push(item);
last = item;
console.log("Added Match: "+item);
}
if(!wasMatch){
console.log("Not matched: " + item);
if(listcurrent.length >= maxitems){
list_matches.push(listcurrent);
}
// reset to null
last = -1;
listcurrent = [];
}
}
console.log(list_matches);
console.log("Cols: " + grid.length);
}
Expected Results: from [2,2,2,5,5,5,3,3,3,3];
0: 222
1: 555
2: 3333
Current output is:
0: 222 and thats it
You could take a temporary array for collecting the same values and push this array if the length has the wanted minimum length.
function getMore(array, min) {
var result = [],
temp;
array.forEach((v, i, a) => {
if (v !== a[i - 1]) return temp = [v];
temp.push(v);
if (temp.length === min) result.push(temp);
});
return result;
}
console.log(getMore([2, 2, 2, 5, 5, 5, 3, 3, 3, 3], 3));
you can do something like this:
var grid = [ 1, 1, 2, 3, 4, 5 ];
var hashMap = {};
for( var i = 0; i < grid.length; i++ ) {
if( hashMap.hasOwnProperty( grid[i] ) ) {
hashMap[ grid[i] ]++;
} else {
hashMap[ grid[i] ] = 1;
}
}
it will helps you.
//toLowerCase for get unique on words, not on character. if i ignore this, it will return two words=> developers. and developers
//first Split and join for remove '.' character form text and finally last split is for convert string to an Array of words that splited by Space character
let uniqWords = Array.from(new Set(text));
//using Set to get unique words and convert it to Array to do more on Array.
let count = {};
// declare varriable for store counts of words.
uniqWords.map(item => {
count[item] = text.filter(elem => {
//create property with the name of words and filter common words to an Array
return elem == item
}).length
//get Array length for get words repeated count.
})
console.table(count)
//log Result into Console
Another solution using Array.prototype[reduce/map/filter]
const someArray = [2, 2, 2, 5, 5, 5, 3, 3, 3, 3, 9, 9];
console.log(aggregate(someArray));
function aggregate(arr) {
return arr
// retrieve unique values
.reduce((acc, val) => !acc.includes(val) && acc.concat(val) || acc, [])
// use unique values to map arr values to strings
// if number of matches >= 3
.map(val => {
const filtered = arr.filter(v => v == val);
return filtered.length > 2 ? filtered.join("") : false
})
// filter non falsy values
.filter(val => val);
}
I have an inventory of items in my game and the player will need to have the ability to auto-sort the items based on several criteria being name,quantity and type.
// create the Inventory grid
var InventoryWidth = 2;
var InventoryHeight = 4;
var Inventory = new Array(InventoryWidth);
for (var i = 0; i < InventoryWidth; i++) {
Inventory[i] = new Array(InventoryHeight);
}
// set the Items & default quantities
Inventory[0][0] = "Potion";
Inventory[1][0] = 2;
Inventory[0][1] = "Elixir";
Inventory[1][1] = 9;
Inventory[0][2] = "Antidote";
Inventory[1][2] = 5;
Inventory[0][3] = "Ether";
Inventory[1][3] = 1;
// function for sorting items
function Sort2D(array2D, byColumn, ascending) {
// sort, seems I am using the wrong sorting function or my approach is wrong here:
// not sure how to do ASC/DESC as well
array2D.sort(function(a, b)
{
if(a[0] === b[0])
{
var x = a[byColumn].toLowerCase(), y = b[byColumn].toLowerCase();
return x < y ? -1 : x > y ? 1 : 0;
}
return a[0] - b[0];
});
}
// sort all rows by first column: "name", setting to 1 should compare and sort the quantities instead
Sort2D( Inventory, 0, true);
// print grid contents
var output = "";
for(var i = 0; i < InventoryHeight; i++) {
if (i == 0) {
output += " | name | own |";
}
for(var j = 0; j < InventoryWidth; j++) {
if (j == 0) {
output += "\n"+i+"|";
}
output+=Inventory[j][i];
if (j >= Inventory[0].length-1) {
output += "|\n";
} else {
output += ", ";
}
}
}
console.log(output);
However I can't seem to figure out how to sort the grid like a table of items.
I'd need it to sort the row order by a chosen column and the ability to have it in ASC/DESC order. How would I go about this?
To sort an array alphabetically, you just need to use the localeCompare method. Numbers have their own version and that can be confusing, so we coerce the variable before comparing it.
function sortAlphabetically(a, b) {
return String(a).localeCompare(b);
}
["cat", "apple", "dog", "beef"].sort(sortAlphabetically);
// -> ["apple", "beef", "cat", "dog"]
I think the main problem you're having is actually with the way you've created your array. At the moment, your array looks like this:
var inventory = [
["Potion", "Elixir", "Antidote", "Ether"],
[2, 9, 5, 1]
];
That means there's no association between "Potion" and 2, other than the array indicies. I think you'll have much better luck if you adjust the array to look like this.
var inventory = [
["Potion", 2],
["Elixir", 9],
["Antidote", 5],
["Ether", 1]
];
Sorting that is much easier. As a bonus, running the .concat() method will clone the array before trying to sort it so the original data isn't modified and having the function return the data in ascending order by default is more conventional.
function sort2D(array, byColumn, isDescending) {
var sorted = array.concat().sort(function (a, b) {
return typeof a[byColumn] === "string"
? sortAlphabetically(a[byColumn], b[byColumn])
: a[byColumn] - b[byColumn];
});
return isDescending
? sorted.reverse()
: sorted;
}
sort2D(inventory, 0);
// -> [ ["Antidote", 5], ["Elixir", 9], ["Ether", 1], ["Potion", 2] ]
sort2D(inventory, 0, true);
// -> [ ["Potion", 2], ["Ether", 1], ["Elixir", 9], ["Antidote", 5] ]
sort2D(inventory, 1);
// -> [ ["Ether", 1], ["Potion", 2], ["Antidote", 5], ["Elixir", 9] ]
I hope that helps.
Update:
Logging out your information becomes easier as well:
var output = inventory
.map(function (inv) {
return "| " + inv.join(" | ") + " |";
})
.join("\n");
console.log("| name | own |\n" + output);
Update 2:
Here's how to sort the old data.
function sort2D(array, byColumn, isDescending) {
// Step 1: sort the part of the array you're trying to sort.
var preSort = array[byColumn].concat().sort(function (a, b) {
return typeof a === "string"
? sortAlphabetically(a, b)
: a - b;
});
if (isDescending) {
preSort = preSort.reverse();
}
// Step 2: create a new, sorted array with your sorted column.
var sorted = [];
sorted[byColumn] = preSort;
// Step 3: create a map to show how the array way sorted.
var sortMap = {};
preSort.forEach(function (item, i) {
sortMap[array[byColumn].indexOf(item)] = i;
});
// Step 4: manually sort the other items of the array.
array.forEach(function (info, i) {
var copy = [];
if (i !== byColumn) {
info.forEach(function (item, j) {
copy[sortMap[j]] = item;
});
sorted[i] = copy;
}
});
// Step 5: return the newly sorted array.
return sorted;
}
My matrix / 2d array looks like this. * | *
I want to get this result
| |
Y Y
[
[0,0,0,0], [
[0,1,0,2], ---> [1,0,2],
[0,2,3,0], [2,3,0],
[0,5,0,0] [5,0,0]
] [
I'd like to remove all rows / cols if their values are ALL equal.
0 1 2 3 4
1 A A A A --> remove col 1
2 B B B B
3 B X B C
4 A B O B
0 1 2 3 4
1 A A C A
2 B B C B
3 B X C C
4 A B C B
|
|
Y
remove row 3
My idea was to use a function like you can find below but my code doesn't seems to work.
Checking "equality" for the X-direction works with no problems, but I have no clue what's the problem with the Y-direction. Obviously it's not working that well :p
my function:
var myarray=[
[0,0,0,0],
[1,0,0,0],
[1,0,0,0],
[1,0,0,0]
]
remove_equal_rows(myarray)
function remove_equal_rows(array) {
/*
x direction --> (working)
*/
var statusX=true;
for (var i=0; i<array.length;i++) {
for (var j = 1; j < array[i].length; j++) {
if (array[i][j] !== array[i][0]) {
statusX=false;break;
} else statusX=true
}
console.log('remove col "'+i+'": ' + statusX)
}
console.log('-------')
/*
y direction --> (not working)
*/
var statusY=true;
for (var i=0;i<array[0].length;i++) {
for (var j = 1; j < array[i].length; j++) {
if (array[j][i] !== array[j][0]) {
statusY=false;break;
} else statusY=true
}
console.log('remove row "'+i+'": ' + statusY)
}
}
Independent removal of rows and columns:
Remove the columns and rows while using the original unaltered matrix as reference:
function remove(matrix) {
let newMatrix = matrix.filter(row => row.some(e => e != row[0])) // filter the rows that have different values
.map(row => row.slice(0)); // copy them into newMatrix (so the original matrix isn't affected by altering them (the rows))
if(newMatrix.length === 0) return newMatrix; // if newMatrix turned out to be rowless (then just retrun it without attempting to clean the columns)
for(var i = newMatrix[0].length - 1; i >= 0; i--) { // for each column (looping backwards so that removing column won't affect the index i)
var first = matrix[0][i]; // getting the value of the i-th column of the first row
if(matrix.every(row => row[i] === first)) { // if all rows have the same value as first for the i-th column
newMatrix.forEach(row => row.splice(i, 1)); // then remove the i-th item (column) from each row
}
}
return newMatrix;
}
var result = remove([
[0,0,0,0],
[1,0,0,0],
[1,0,5,0],
[1,0,0,0]
]);
console.log(result.join("\n"));
Dependent removal of rows and columns:
Depending on the order of removing either rows or columns, one may get different results:
/* Same code as before except that we now have different functions:
* removeRows: that take a matrix and remove rows that have the same values
* removeColumns: that take a matrix and remove columns that have the same values
* depending on wether to call removeRows or removeColumns, you may get different results as shown in an example bellow. (You my call removeRows then removeColumns then call removeRows again and get a different result et cetera...)
*/
function removeRows(matrix) {
return matrix.filter(row => row.some(e => e != row[0]));
}
function removeColumns(matrix) {
if (matrix.length === 0) return matrix;
for (var i = matrix[0].length - 1; i >= 0; i--) {
var first = matrix[0][i];
if (matrix.every(row => row[i] === first)) {
matrix.forEach(row => row.splice(i, 1));
}
}
return matrix;
}
console.log("Removeing rows then columns:");
var result = removeRows([
[0, 0, 0, 0],
[1, 0, 0, 0],
[1, 0, 5, 0],
[1, 0, 0, 0]
]);
result = removeColumns(result);
console.log(result.join("\n"));
console.log("Removeing columns then rows:");
var result = removeColumns([
[0, 0, 0, 0],
[1, 0, 0, 0],
[1, 0, 5, 0],
[1, 0, 0, 0]
]);
result = removeRows(result);
console.log(result.join("\n"));
Notes:
To check if a row has different values, I used some to check if there is some other value in the row that is different from the first element in the row.
To check if a column i has the same values, I used every to check that the i-th element of every row is equal to the i-th element of the first row.
Technically, you were checking the rows again in the second pair of loops. I'm pretty sure this is how it should have been written.
var statusY=true;
for (var i=0;i<array[0].length;i++) {
for (var j = 1; j < array.length; j++) {
if (array[j][i] !== array[0][i]) {
statusY=false;break;
} else statusY=true
}
console.log('remove row "'+i+'": ' + statusY)
}
You can the rows by using Array#filter and converting each array to a Set. If the size of the set is 1, the array should be removed.
To filter the columns, it's easier to rebuild the grid from scratch. Iterate the 1st row with Array#reduce. As accumulator initialize a new grid using Array#from. For each column create a Set from the original column (before filtering the rows), if the size of the set is greater than 0, push it's items to the new grid using Array#forEach.
const myarray = [
[0,0,0,0],
[1,0,0,0],
[1,0,0,0],
[1,0,0,0]
];
const filteredRows = myarray.filter((arr) => new Set(arr).size !== 1); // if a the set of the row contains only 1 item it should be remove
const filteredColumns = (filteredRows[0] || []).reduce((r, _, i) => { // iterate the 1st row
const keep = new Set(myarray.map((arr) => arr[i])).size > 1; // if a the set of the column in the original grid contains more than 1 item, it should be kept
keep && filteredRows.forEach((arr, j) => r[j].push(arr[i])); // if we keep it, and the column to the grid
return r;
}, Array.from({ length: filteredRows.length }, () => [])); // initialize with an empty grid
console.log(filteredColumns);
try this: (first row 0 will be removed then col0 and col 2 will be removed)
var myarray=[
[0,0,0,0],
[1,0,2,0],
[1,1,2,1],
[1,0,2,0]
]
remove_equal_rows(myarray)
function remove_equal_rows(myArray) {
/*
x direction --> (working)
*/
var resultX = [];
for (var i=0; i<myArray.length;i++) {
statusX = true;
for (var j = 1; j < myArray[i].length; j++) {
if (myArray[i][j] !== myArray[i][0]) {
statusX=false;break;
}
}
if (statusX) { resultX.push(i); }
}
console.log('rows indexes to remove : ', resultX);
resultX.map(function(item) { myArray.splice(item,1); });
console.log('-------', myArray);
/*
y direction --> (now working)
*/
var statusY, resultY = [];
for (var i=0;i<myArray.length;i++) {
statusY = true;
for (var j = 1; j < myArray.length; j++) {
console.log(j, i, myArray[j][i]);
if (myArray[j][i] !== myArray[0][i]) {
statusY=false;break;
}
}
if (statusY) {resultY.push(i);}
}
console.log('cols indexes to remove : ', resultY);
resultY.map(function(item) { myArray.splice(item,1); });
console.log('-------', myArray);
}
checkout this fiddle: https://jsfiddle.net/a9qvtuu4/
I implemented this recursively where it runs the result array through the uniqueifier repeatedly until no modifications are made.
Making the X-direction rows distinct is more straightforward than columns, so you can handle distinct columns by rotating the matrix -> distinct X-direction -> rotate back.
var masterArr = [
[0,0,0,0],
[1,0,0,0],
[1,0,3,0],
[1,0,0,4]
];
function uniqueColRow(arr) {
if(arr.length === 0 || arr[0].length === 0) {
return arr;
}
var distinctRows = arr.filter((x) => { return x.filter(unique).length > 1; });
var flip = rotateArr(distinctRows);
var distinctCols = flip.filter((x) => { return x.filter(unique).length > 1; });
var resultArr = rotateArr(distinctCols);
if(arr.length !== resultArr.length || arr[0].length !== resultArr[0].length) {
console.log('running again with:');
console.log(resultArr);
return uniqueColRow(resultArr);
}else {
return resultArr;
}
}
console.log('Original:');
console.log(masterArr);
console.log('\n');
var result = uniqueColRow(masterArr);
console.log('\nFinal:')
console.log(result);
function rotateArr(arr) {
return arr[0].map((col, i) => arr.map(row => row[i]));
}
function unique(item, i, self) {
return self.indexOf(item) === i;
}
Fiddle has slightly easier to read console output.
Great question - fun puzzle!
I have string like the following:
11222233344444445666
What I would like to do is output the number followed the times it was displayed:
112433475163
Question is, I want this to be efficient. I can store this in an object as the following:
1: { id: 1, displayed: 2},
2: { id: 2, displayed: 1},
3: { id: 3, displayed: 2},
etc.
I can access this object and increment displayed.
My issues is, there is no guarantee in the order. I would like to store the keys in the order they are in the string. How do I accomplish the importance of the order in the object?
This is a proposal for run length coding with an array which holds infomation about one charcter and the count of it:
{
"char": "1",
"count": 2
},
var string = "11222233344444445666",
array = function () {
var r = [], o = {};
string.split('').forEach(function (a, i, aa) {
if (a !== aa[i - 1]) {
o[a] = { char: a, count: 0 };
r.push(o[a]);
}
o[a].count++;
});
return r;
}(string);
document.write('<pre>' + JSON.stringify(array, 0, 4) + '</pre>');
Quick solution with for loop:
var str = "7771122229933344444445666",
obj = {},
len = str.length,
val = null,
count_str = "",
key = "";
for (var i = 0; i < len; i++) {
val = str[i], key = 'k' + val;
if (!obj[key]) {
obj[key] = {'id': val, 'displayed': 1};
} else {
obj[key].displayed++;
}
}
for (var p in obj) {
count_str += obj[p]['id'] + obj[p]['displayed'];
}
console.log(count_str); // "7312249233475163"
because you have such a small set of distinct numbers, I seen no reason why you can't use a array (yeah it's not super ideal memorywise if you skip values and it becomes sparse, but for such a small subset it won't affect you enough to worry of it). Then you can use (number-1) as the index and increment that number as needed.
var counts = [];
var str = "11222233344444445666";
for(var i in str){
var index = parseInt(str[i])-1
counts[index] = (counts[index]||0)+1;
}
for(var i in counts){
var which = 1+parseInt(i);
var count = counts[i];
console.log("# of " + which +"'s: "+count);
}
https://jsfiddle.net/ga0fqpqn/
note: You shouldn't need the parseInt(i)... just +i should work but I think jsfiddle has a bug with it about it defaulting i to handle like a string.
You could store an additional array with the order of the numbers, which you only append to if the object doesn't yet contain the given number. Then once you're done counting, iterate through that array and output the number and the count from the lookup dictionary.
var chars = "1234576123452345".split("");
var order = [];
var hash = {};
chars.forEach(function(char) {
if (!hash[char]) {
hash[char] = 1;
order.push(char);
} else {
hash[char]++;
}
});
console.log(order.map(function(char) {
return char + hash[char];
}).join(""));
// "12233343537161"
I am trying to create a matrix table. The values to be plugged into the matrix will be user input from an html table (basically a unique pairing table which pairs two elements at a time and for each pair a user can select which he prefers and by how much it is prefered on a scale of 1-9 using radio buttons). it is the preferences i.e. 1-9 that gets plugged into the matrix table and the number of unique pairing that detemines the lenght of the matrix.
when the matric is generated i want to have something like this:
0 1 2 3 4 sum
1 [1] [6] [2] [8] 17
2 [ ] [1] [9] [4] 15
3 [ ] [ ] [1] [7] 8
4 [ ] [ ] [ ] [1] 1
The problem is now i want to get the values of clicked radios into the matix. I know how to get it but just don't know how to fit it into the matrix. Here is the code I have for now, pls ask me questions if needed thanks:
$(function(){
var tableLenght = new Array();
$('#matrix').click(function(){
var counter = 0;
$("#riskForm tr").each(function(){
//ignores the header of the table (the title)
if(counter >=1){
tableLenght.push($(this).closest('tr').children("td:eq(1)").text());
}
counter++;
});
// get unique attributes of in our table
var uniqueList = new Array();
//push first element onto list
uniqueList.push(tableLenght[0]); //pushes current elem onto the array
var cur = tableLenght[0]; //sets first element by default
for(var i = 1; i < tableLenght.length; i++){ //loops through the whole lenght of our array
if(cur != tableLenght[i]){//checks if the current is not same as the next one
cur = tableLenght[i]; //sets the new elemt
uniqueList.push(tableLenght[i]); //pushes onto the array
}
}
alert(uniqueList); //alerts only the unique table rows in the tableLenght array
var myArray = new Array(uniqueList);
for (var i = 0; i < uniqueList; i++) {
myArray[i] = new Array(uniqueList);
for (var j = 0; j < uniqueList; j++) {
myArray[i][j] = '';
}
}
});
//to show/get the values of selected radio buttons
function showValues() {
var fields = $( ":input").serializeArray();
$( "#results" ).empty();
jQuery.each( fields, function( i, field ) {
$( "#results" ).append( field.value + " " );
});
}
$( ":checkbox, :radio" ).click( showValues );
showValues();
$('#display').click(function (n) {
document.location.href="trialIndex.php"
});
});
Your help is much appreciated!
You can push a value to an array, for example:
var a = [];
a.push(1);
a.push(2);
console.log(a); // [1, 2]
You can set it based on index:
var a = [];
a[0] = 1;
a[1] = 2;
console.log(a); // [1, 2]
To create a multi dimensional array you can simply push arrays to one array.
var a = [1,2,3];
var b = [4,5,6];
var c = [];
c.push(a);
c.push(b);
console.log(c); // [[1, 2, 3], [4, 5, 6]]
I think you are trying to implement the AHP algorithm here. It is quite complex to write the whole code here and how it'll work but here is a link of an already exiting work on AHP. Hope it helps: https://github.com/humbertoroa/ahp