Javascript : how to slice an array of objects? - javascript

So, I have an array of objects like this:
for(var i=0; i<travelcard_table.length;i++){
var table_row = travelcard_table.eq(i);
var ii = 0;
passenger_info[i] = {};
table_row.find("td").each(function() {
passenger_info[i][table_keys[ii]] = $(this).text();
ii++;
});
}
passenger_info[0]['First name'] = "John"; etc..
passenger_info[1]['First name'] = "Chuck"; etc..
Im trying to split this to smaller arrays of objects every 10 entries, so Its something like this:
var size = 10;
for (var i=0; i<passenger_count; i+=size) {
var smallarray = passenger_info.slice(i,i+size); << "Error: Slice is not a function"
console.log(smallarray);
// do something with smallarray
}
How to achieve this?

var passenger_info = [[], []];
passenger_info[0]['First name'] = "John";
passenger_info[1]['First name'] = "Chuck";
var sliced = passenger_info.slice(0,1);
alert(sliced[0]['First name']);
This alerts 'John', because passenger_info is an Array of Array objects and you are attaching properties to the array object and not to its items.
for an array of objects it should be:
var passenger_info = [ {} , {}];
passenger_info[0].firstname = "John";
passenger_info[1].firstname = "Chuck";
var sliced = passenger_info.slice(0,1);
alert(sliced[0].firstname);

like this you can workout
for (var i=0; i<passenger_info.length; i+=10) {
var smallArray = [];
for(var j=0;j<10 && i+j < passenger_info.length;j++) {
smallArray.push(passenger_info[i+j]);
}
console.log(smallArray);
}
for using slice you can do like this
for (var i=0; i<passenger_info.length; i+=10) {
var smallArray = [],ls;
for(var j=0;j<10 && i+j < passenger_info.length;j++) {
ls = i+j;
}
smallArray = passenger_info.slice(i,ls+1);
console.log(smallArray);
}

Related

Javascript - JSON String to Array

This is driving me mad, I have a JSON string that looks like so:
[["OX", "139.38"], ["LE", "131.28"], ["SA", "105.45"]]
I want to convert this to an array so that I can I can take advantage of indexOf:
alert(myArray.indexOf("LE"));
I've tried to convert my JSON string to an array using JSON.parse(myJSON) and jQuery.parseJSON(myJSON) but neither work.
How can I create an array from my JSON string? I'm happy to set up a loop just not sure how.
This works in chrome console:
var s = '[["OX", "139.38"], ["LE", "131.28"], ["SA", "105.45"]]';
var a = JSON.parse(s);
// a = [["OX", "139.38"],["LE", "131.28"],["SA", "105.45"]]
If you want to create a data structure to lookup the values by the keys:
var dict = {};
for (var i=0; i<a.length; i++){
dict[a[i][0]] = a[i][1];
}
Now dict looks like this:
//dict = {OX:"139.38", LE:"131.28", SA:"105.45"}
and we can index into it with the keys
dict['LE'] // = "131.28"
This will convert it like this [[""OX", "139.38"], ["LE", "131.28""]] -> ["OX", "LE"]
var newArr = [];
for(var i = 0; i < myArr.length; i++) {
newArr.push(myArr[i][0]);
}
This will convert it like this [[""OX", "139.38"], ["LE", "131.28""]] -> ["OX", "139.38", "LE", "131.28"]
var newArr = [];
for(var i = 0; i < myArr.length; i++) {
var tempArr = myArr[i];
for(var j = 0; j < tempArr.length; j++) {
newArr.push(tempArr[j]);
}
}
Now you can use indexOf.
If you want to get index at outter array:
var x = '[["OX", "139.38"], ["LE", "131.28"], ["SA", "105.45"]]';
var y = JSON.parse(x);
function getIndexByKey(key,array){
for(var i=0, len = array.length; i<len;i++){
if(array[i][0] === key){
return i;
}
}
}
function getIndexByVal(val,array){
for(var i=0, len = array.length; i<len;i++){
if(array[i][1] === val){
return i;
}
}
}
calling it:
getIndexByKey('OX', y); //0
getIndexByKey('LE', y); // 1
getIndexByKey('SA', y) // 2
getIndexByVal('139.38', y); //0
...

How to match string values of two arrays using javascript

I have two arrays
var arr1 = ['wq','qw','qq'];
var arr2 = ['wq','wq','wq','qw','qw','qw','qw','qq','qq'];
Below what i did is matching arr1 values with arr2. If the array contains same values i pushed the values into newArr.
var newArr = [];
for (var i=0;i<arr1.length;i++) {
newArr[i] = [];
}
for (var i=0;i<arr2.length;i++) {
for (var j=0;j<arr1.length;j++) {
if (arr2[i].indexOf(arr1[j]) != -1)
newArr[j].push(arr2[i]);
}
}
console.log(newArr[1]); //newArr[0] = ['wq','wq','wq'];//In second output array newArr[1] = ['qw','qw','qw','qw'];
Is there any easy way to solve this without using two for loops. Better i need a solution in javascript
Maybe use indexOf():
var count = 0;
for (var i = 0; i < arr1.length; i++) {
if (arr2.indexOf(arr1[i]) != -1) {
count++;
// if you just need a value to be present in both arrays to add it
// to the new array, then you can do it here
// arr1[i] will be in both arrays if you enter this if clause
}
}
if (count == arr1.length) {
// all array 1 values are present in array 2
} else {
// some or all values of array 1 are not present in array 2
}
Your own way wasn't totally wrong, you just had to check if the element was index of the array and not of an element in the array.
var arr1 = ['wq','qw','qq'];
var arr2 = ['wq','wq','wq','qw','qw','qw','qw','qq','qq'];
var newArr = [];
for (var i in arr1) {
newArr[i] = [];
}
for (var i in arr2) {
var j = arr1.indexOf(arr2[i]);
if (j != -1) {
newArr[j].push(arr2[i]);
}
}
This way you removed the nested for loop and it still gives you the result you asked for.
var arr1 = ['wq','qw','qq','pppp'];
var arr2 = ['wq','wq','wq','qw','qw','qw','qw','qq','qq'];
function intersect(a, b) {
var d = {};
var results = [];
for (var i = 0; i
d[b[i]] = true;
}
for (var j = 0; j
if (d[a[j]])
results.push(a[j]);
}
return results;
}
var result_array = intersect(arr1,arr2);
// result_array will be like you want ['wq','wq','wq'];

javascript/jquery build array from counted array

Hey i have a simple question i cant find an answer,
i´m trying to generate some raw-data for a chart
lets say i have an array like :
[1,0,0,1,2,0]
is there a way to make an array out of it that has nested arrays that represent the count of duplicate entrys ?
[[0,3],[1,2],[2,1]]
here is some code that does the trick, but saves the count as objects
var array = [1,0,0,1,2,0];
var length = array.length;
var objectCounter = {};
for (i = 0; i < length; i++) {
var currentMemboerOfArrayKey = JSON.stringify(array[i]);
var currentMemboerOfArrayValue = array[i];
if (objectCounter[currentMemboerOfArrayKey] === undefined){
objectCounter[currentMemboerOfArrayKey] = 1;
}else{
objectCounter[currentMemboerOfArrayKey]++;
}
}
but objectCounter returns them like
{0:3,1:2,2:1}
but i need it as an array i specified above ?
for any help, thanks in advance
Try
var array = [1, 0, 0, 1, 2, 0];
function counter(array) {
var counter = [],
map = {}, length = array.length;
$.each(array, function (i, val) {
var arr = map[val];
if (!arr) {
map[val] = arr = [val, 0];
counter.push(arr);
}
arr[1] += 1;
})
return counter;
}
console.log(JSON.stringify(counter(array)))
Demo: Fiddle
You can turn your object into an array easily:
var obj = {0:3,1:2,2:1};
var arr = [];
for (var key in obj) {
// optional check against Object.prototype changes
if (obj.hasOwnProperty(key)) {
arr.push([+key, obj[key]]);
}
}
Note: The object keys are strings, so i converted them back to numbers when placed in the array.
Functional way of doing this, with Array.reduce and Array.map
var data = [1,0,0,1,2,0];
var result = data.reduce(function(counts, current) {
counts[current] = current in counts ? counts[current] + 1: 1;
return counts;
}, {});
result = Object.keys(result).map(function(current){
return [parseInt(current), result[current]];
});
console.log(result);
Output
[ [ 0, 3 ], [ 1, 2 ], [ 2, 1 ] ]
Try:
var data = [1,0,0,1,2,0];
var len = data.length;
var ndata = [];
for(var i=0;i<len;i++){
var count = 0;
for(var j=i+1;j<len;j++){
if(data[i] == data[i]){
count ++;
}
}
var a = [];
a.push(data[i]);
a.push(count);
ndata.push(a);
}
console.log(ndata)
DEMO here.
First you need to map the array to an associative object
var arr = [1,0,0,1,2,0];
var obj = {};
for (var i = 0; i < arr.length; i++) {
if (obj[arr[i]] == undefined) {
obj[arr[i]] = 0;
}
obj[arr[i]] += 1;
}
Then you can easily turn that object into a 2d matrix like so:
arr = [];
for (var k in obj) {
arr.push([k, obj[k]]);
}
alert(JSON.stringify(arr));
Your existing object can be turned into an array with a simple for..in loop. Also your existing code that produces that object can be simplified. Encapsulate both parts in a function and you get something like this:
function countArrayValues(array) {
var counter = {},
result = [];
for (var i = 0, len = array.length; i < len; i++)
if (array[i] in counter)
counter[array[i]]++;
else
counter[array[i]] = 1;
for (i in counter)
result.push([+i, counter[i]]);
return result;
}
console.log( countArrayValues([1,0,0,1,2,0]) );
Demo: http://jsfiddle.net/hxRz2/

making an array from other array items

I have the following problem:
var price = ['4','5','8','12']
var produce = ['kiwi','orange','apple','banana']
var stock = ['yes','no','no','yes']
i need to group them so that the end output is on array in the following format:
var store = [ ['4','kiwi','yes'],['5','orange','no'], ...]
im so confused as in how to make one array with these values into a 2d array. thanks
Using JavaScript with some overkill :):
var price = ['4','5','8','12']
var produce = ['kiwi','orange','apple','banana']
var stock = ['yes','no','no','yes']
// if the lengths/size of the above arrays are the same
var store = [];
for(var i = 0, len = price.length; i < len; i++) {
store.push([price[i], produce[i], stock[i]]);
}
// if the lengths/size of the above arrays aren't the same and you want the minimum full entries
var storeMin = [];
for(var i = 0, len = Math.min(price.length, produce.length, stock.length); i < len; i++) {
storeMin.push([price[i], produce[i], stock[i]]);
}
// if the lenghts/size of the above arrays aren't the same and you want the maximum entries with defaulting missing values to null
// replace the nulls by any default value want for that column
var storeMax = [];
for(var i = 0, pLen = price.length, prLen = produce.length, sLen = stock.length, len = Math.max(pLen, prLen, sLen); i < len; i++) {
storeMax.push([pLen>i?price[i]:null, prLen>i?produce[i]:null, sLen>i?stock[i]:null]);
}
var price = ['4','5','8','12']
var produce = ['kiwi','orange','apple','banana']
var stock = ['yes','no','no','yes']
var store = [];
$.each(price,function(ind,elm) {
store.push([elm,produce[ind],stock[ind]]);
});
console.log(store);

Creating objects in for loop. I missing the mark a bit

I would like to have a for loop create objects as the children of a parent object. Usually, I would declare the object without using the for loop like this:
var mObj = {};
mObj.obj1 = {};
mObj.obj2 = {};
mObj.obj3 = {};
mObj.obj3.firstname = "john";
mObj.obj3.lastname = "superfly";
Now lets say I would like to employ a for loop to create the children objects of a parent object "mObj".
This is where I am going wrong:
var mArr = ["firstname","lastname","email"]; // This array holds the keys for the objects
var mObj = {};
var len = (mArr.length);
for(var i=0; i<len; i++){
var obj+i = {}
mObj = obj+i;
mObj.obj + i.mArr[i] = ""
}
So the outcome of this would be:
mObj.obj1.firstname = "";
mObj.obj2.lastname = "";
mObj.obj3.email = "";
I just cannot seem to name the object with counter that is being created within for loop like:
obj1
obj2
obj3
Any help would highly be appreciated.
Thanks.
var obj+i = {} is invalid syntax.
Try this:
mObj['obj' + i] = {};
If i == 1, this gives
mObj['obj1'] = {};
Which is equiavlent to:
mObj.obj1
But when constructing dynamically, you have to use the
mObj['obj' + i]
Formatting.
var mArr = ["firstname","lastname","email"],
mObj = {},
len = (mArr.length),
i = 0;
for(; i<len; i++){
myObj['obj' + i] = {}
myObj['obj' + i].mArr[i] = ""
}
You need to use the bracket syntax to assign a dynamic variable. For example:
var sampleObj = {};
for(var j = 0; j < 3; j++)
{
sampleObj["obj" + j] = { test: j };
}
This should produce the following object:
{
"obj1" : { test: 1 },
"obj2" : { test: 2 },
"obj3" : { test: 3 }
}
After running the loop then, you could validly use this statement:
var testVal = sampleObj.obj1.test;

Categories

Resources