Check if a particular sequence of array elements is empty - javascript

["Order", "Id", "Comment", "Id_type", "UbAction", "Ub_Factor", "LbAction","Lb_Factor",
"6", "12321", "3rd test", "Industry", "0.23", "true", "0", "false",
"22", "sss", "4", "Sector", "0", "true", "0.565676", "true",
"99", "277906", "", "Sector", "1", "true", "0", "true",
"3", "416921", "correction check", "Industry", "1", "true", "0", "false"]
I have this array shown above. The first eight elements are the header. So I will remove those using splice.
I need to check if the elements 8,16,24 AND 9,17,25 AND 11,19,27 are empty. How can i loop through this elements dynamically. The sequence of elements are weird. Can someone please suggest how to check if these above element number is the current one which is being looped.

Thanks guys for the replies. I worked on it a bit and the below code worked for me pretty nicely...
var count = 0;
var array2= [0,1,3,4,6];
function checkArray5(cell_data){
for(var i=8;i<cell_data.length; i++) {
for (var j=0;j<5;j++)
{
if (i%8 == array2[j])
{
if(cell_data[i] ==="") {
console.log(count++);
}
}
}
}
}
checkArray5(array);

Use the % operator to search for the indexes that return 0, 1 and 3 respectively:
var table = ["Order", "Id", "Comment", "Id_type", "UbAction", "Ub_Factor", "LbAction","Lb_Factor",
"6", "12321", "3rd test", "Industry", "0.23", "true", "0", "false",
"22", "sss", "4", "Sector", "0", "true", "0.565676", "true",
"99", "277906", "", "Sector", "1", "true", "0", "true",
"3", "416921", "correction check", "Industry", "1", "true", "0", "false"];
var index = 0;
var columns = 8;
var cells = table.slice(columns);
var len = cells.length;
for (;index < len; index++) {
var mod = index % columns;
switch (mod) {
case 0:
case 1:
case 3:
isEmpty(cells[index]);
break;
}
}

Here is my suggestion:
var myArr = ["Order", "Id", "Comment", "Id_type", "UbAction", "Ub_Factor", "LbAction", "Lb_Factor",
"6", "12321", "3rd test", "Industry", "0.23", "true", "0", "false",
"22", "sss", "4", "Sector", "0", "true", "0.565676", "true",
"99", "277906", "", "Sector", "1", "true", "0", "true",
"3", "416921", "correction check", "Industry", "1", "true", "0", "false"];
// added or remove elements to be checked if empty.
var emptyElementChk = [8, 9, 11, 16, 17, 19, 24, 25, 27];
for (var i = 0; i < emptyElementChk.length; i++) {
//All checked array listed
console.log("Key : " + emptyElementChk[i] + " value: " + myArr[emptyElementChk[i]]);
if (myArr[emptyElementChk[i]] == "") {
// empty arrays action
} else {
// none empty arrays action
}
};

Related

How to convert 1D array into 2D array with predefined positions in JavaScript? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
So, Here is my 1D array,
"seats": [
{
"available": "true",
"column": "0",
"name": "L1",
"row": "0",
},
{
"available": "true",
"column": "1",
"name": "L2",
"row": "0",
},
{
"available": "true",
"column": "0",
"name": "L3",
"row": "1",
},
{
"available": "true",
"column": "1",
"name": "L4",
"row": "1",
},
{
"available": "true",
"column": "0",
"name": "L5",
"row": "2",
},
{
"available": "true",
"column": "1",
"name": "L6",
"row": "2",
},
{
"available": "true",
"column": "0",
"name": "L7",
"row": "3",
},
{
"available": "true",
"column": "1",
"name": "L8",
"row": "3",
},
{
"available": "true",
"column": "0",
"name": "L9",
"row": "4",
},
{
"available": "true",
"column": "1",
"name": "L10",
"row": "4",
},
];
So, above is the sample array, from the above i need to create 2D array and display the name on each.
Expected output:
CR CR CR CR
30-20 10-00
31-21 11-01
In this C - column and R is row for reference !
And so on, how to convert 1d into 2d and position the elements according to the row and columns from the array ?
My code trying's:
seats(list, elementsPerSubArray){
var matrix = [], i, k;
for (i = 0, k = -1; i < list.length; i++) {
if (i % elementsPerSubArray === 0) {
k++;
matrix[k] = [];
}
matrix[k].push(list[i]);
}
for(var i = 0; i < matrix.length; i++) {
var cube = matrix[i];
for(var j = 0; j < cube.length; j++) {
console.log("s");
}
}
}
Its giving a straight line of outputs with missing outputs !kindly help,
You could assign name to the given row/columns.
const
data = [{ available: "true", column: "0", name: "L1", row: "0" }, { available: "true", column: "1", name: "L2", row: "0" }, { available: "true", column: "0", name: "L3", row: "1" }, { available: "true", column: "1", name: "L4", row: "1" }, { available: "true", column: "0", name: "L5", row: "2" }, { available: "true", column: "1", name: "L6", row: "2" }, { available: "true", column: "0", name: "L7", row: "3" }, { available: "true", column: "1", name: "L8", row: "3" }, { available: "true", column: "0", name: "L9", row: "4" }, { available: "true", column: "1", name: "L10", row: "4" }],
result = data.reduce((r, { column, row, name }) => {
if (!r[row]) r[row] = [];
r[row][column] = name;
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
I used your seats as a basic variable array here.
In column and row attributes you already have the basic keys for a 2d-array, just need to run through it and put every column or every row together.
I did not make any tests other than check if the sub array is undefined
Now you'd have to loop through both dimensions again and print those names
var seats = []; // your content
let newSeats = [];
// rows as first dimension
for (let i = 0; i < seats.length; i++) {
let row = seats[i].row;
if (newSeats[row] === undefined) newSeats[row] = [];
newSeats[row].push(seats[i]);
}
let newSeats = [];
// columns as first dimension
for (let i = 0; i < seats.length; i++) {
let column = seats[i].column;
if (newSeats[column] === undefined) newSeats[column] = [];
newSeats[column].push(seats[i]);
}

Order of Array Elements Causing Error

I have two arrays. Elements of each array are shown as below:
allLabBranches = [{
"labbranchid": "1",
"labname": "Wahab Labs, Islampura Branch, Lahore",
"labtitle": "Wahab Labs Lahore",
"shortname": "WAHB",
"address": "56 Islampura, Lahore",
"landlineno": "04237940445",
"datecreated": "2016-03-11 11:00:00",
"createdbyname": "Jamshaid Sabir",
"createdbyuserid": "1",
"dateupdated": "2016-05-04 00:53:03",
"updatedbyname": "Jamshaid Sabir",
"updatedbyuserid": "1",
"clientgroups_clientgroupsid": "1",
"startdate": "2016-05-04"
}, {
"labbranchid": "2",
"labname": "Wahab Labs, Model Town Branch, Lahore",
"labtitle": "Wahab Labs Lahore",
"shortname": "WAHAB",
"address": "45 Model Town, Lahore",
"landlineno": "04237945485",
"datecreated": "2016-03-11 11:00:00",
"createdbyname": "Jamshaid Sabir",
"createdbyuserid": "1",
"dateupdated": "0000-00-00 00:00:00",
"updatedbyname": "",
"updatedbyuserid": "",
"clientgroups_clientgroupsid": "1",
"startdate": "0000-00-00"
}, {
"labbranchid": "3",
"labname": "Shahdara More Branch",
"labtitle": "Wahab Labs Lahore",
"shortname": "WAHAB",
"address": "Shahdara",
"landlineno": "04237933415",
"datecreated": "2016-03-11 11:48:15",
"createdbyname": "Jamshaid Sabir",
"createdbyuserid": "1",
"dateupdated": "0000-00-00 00:00:00",
"updatedbyname": "",
"updatedbyuserid": "",
"clientgroups_clientgroupsid": "1",
"startdate": "0000-00-00"
}, {
"labbranchid": "4",
"labname": "New Branch",
"labtitle": "Wahab Labs Lahore",
"shortname": "WAHB",
"address": "More Samanabad, Lahore",
"landlineno": "042361561",
"datecreated": "2016-03-11 11:52:06",
"createdbyname": "Jamshaid Sabir",
"createdbyuserid": "1",
"dateupdated": "2016-03-14 15:06:44",
"updatedbyname": "Jamshaid Sabir",
"updatedbyuserid": "1",
"clientgroups_clientgroupsid": "1",
"startdate": "2016-03-14"
}, {
"labbranchid": "5",
"labname": "Test Branch",
"labtitle": "xyz",
"shortname": "sfwe",
"address": "dsfasd",
"landlineno": "sdfasd",
"datecreated": "2016-03-12 00:14:11",
"createdbyname": "Jamshaid Sabir",
"createdbyuserid": "1",
"dateupdated": "2016-08-11 12:54:12",
"updatedbyname": "Jamshaid Sabir",
"updatedbyuserid": "1",
"clientgroups_clientgroupsid": "1",
"startdate": "2016-03-12"
}, {
"labbranchid": "6",
"labname": "Test Branch 2",
"labtitle": "asdfs",
"shortname": "asdfs",
"address": "asdf",
"landlineno": "asdf",
"datecreated": "2016-03-12 12:16:24",
"createdbyname": "Jamshaid Sabir",
"createdbyuserid": "1",
"dateupdated": "0000-00-00 00:00:00",
"updatedbyname": "",
"updatedbyuserid": "",
"clientgroups_clientgroupsid": "1",
"startdate": "2016-03-12"
}, {
"labbranchid": "7",
"labname": "Wahab Labs, Shahdara Branch, Lahore",
"labtitle": "Shahdara",
"shortname": "Shahdara",
"address": "Shahdara",
"landlineno": "0423744915",
"datecreated": "2016-08-11 12:56:27",
"createdbyname": "Jamshaid Sabir",
"createdbyuserid": "1",
"dateupdated": "2016-08-11 12:57:01",
"updatedbyname": "Jamshaid Sabir",
"updatedbyuserid": "1",
"clientgroups_clientgroupsid": "1",
"startdate": "2016-08-01"
}]
Another array elements are:
labsOfUser = [{
"userhasbranchid": "53",
"labbranches_labbranchid": "6",
"usersoflabs_userId": "9"
}, {
"userhasbranchid": "54",
"labbranches_labbranchid": "1",
"usersoflabs_userId": "9"
}, {
"userhasbranchid": "55",
"labbranches_labbranchid": "7",
"usersoflabs_userId": "9"
}, {
"userhasbranchid": "56",
"labbranches_labbranchid": "2",
"usersoflabs_userId": "9"
}]
Now I have a Select Multiple Box and I show some branches as selected and some as not selected. The code is given below:
function populateSelectedLabs() {
$('#labbranchids').empty();
if (allLabBranches.length >= labsOfUser.length) {
for (var i = 0; i < allLabBranches.length; i++) {
for (var j = 0; j < labsOfUser.length; j++) {
if (allLabBranches[i].labbranchid == labsOfUser[j].labbranches_labbranchid) {
$("#labbranchids").append("<option selected='selected' value='" + allLabBranches[i].labbranchid + "'>" + allLabBranches[i].labname + "</option>");
allLabBranches = jQuery.grep(allLabBranches, function(value) {
return value != allLabBranches[i];
});
} //end inner if
} //end inner loop
} //end outer loop
} //end if
for (var i = 0; i < allLabBranches.length; i++) {
$("#labbranchids").append("<option value='" + allLabBranches[i].labbranchid + "'>" + allLabBranches[i].labname + "</option>");
} //end for loop
} //end function
The problem is that array element comparison misses an element which is present in the array but located at different index in the array. The error occurs at following line of code:
if(allLabBranches[i].labbranchid == labsOfUser[j].labbranches_labbranchid){
Kindly help me to know how to compare all the elements in both array?
The reason why certain items are not matched is that you redefine the allLabBranches inside the loop on that same array, making it shorter.
Let's assume that before that change the following is true:
labsOfUser[j-1].labbranches_labbranchid == allLabBranches[i+1].labbranchid
You would expect this equality to be detected later, in the next iteration of the outer loop. But because of the re-assignment to allLabBranches, this value no longer is at index i+1, but at i. This value will no longer be matched during the remaining part of the inner loop (because the matching value is at j-1), and so i will increment for the next iteration of the outer loop. As a consequence this value will never be matched.
You could solve this by iterating backwards through the allLabBranches array, but even better would be to create a hash with the values from the labsOfUser array. This will have better performance.
You can do that like this:
function populateSelectedLabs() {
$('#labbranchids').empty();
// create hash
var hash = {};
for (var j = 0; j < labsOfUser.length; j++) {
hash[labsOfUser[j].labbranches_labbranchid] = 1;
}
allLabBranches = jQuery.grep(allLabBranches, function(value) {
return hash[value.labbranchid];
}).concat(jQuery.grep(allLabBranches, function(value) {
return !hash[value.labbranchid];
}));
for (var i = 0; i < allLabBranches.length; i++) {
$("#labbranchids").append($('<option>')
.val(allLabBranches[i].labbranchid)
.text(allLabBranches[i].labname)
.attr('selected', hash[allLabBranches[i].labbranchid]));
}
}
If the target browsers support ES6, then you could write it like this:
function populateSelectedLabs() {
$('#labbranchids').empty();
var hash = new Set(labsOfUser.map( value => value.labbranches_labbranchid ));
allLabBranches.filter( value => hash.has(value.labbranchid) )
.concat(allLabBranches.filter( value => !hash.has(value.labbranchid) ))
.forEach( value =>
$("#labbranchids").append($('<option>')
.val(value.labbranchid)
.text(value.labname)
.attr('selected', hash.has(value.labbranchid)))
);
}

Merging two json array object based on union and intersection

I am trying to merge two json array with objects as element. You may refer to this plunkr file for both json. I have succesfully retrieve the expected final outcome array id, but I do not know how to form back the expected json as below. I am using underscore js for this purpose.
Note: If object exist in newJson and not in currentJson, after merge, it will be inactive state by default.
I am not sure whether I am using the correct approach. This is what I have try:
var newJsonID = _.pluck(newJson, 'id');
var currentJsonID = _.pluck(currentJson, 'id');
var union = _.union(newJsonID, currentJsonID);
var intersection = _.intersection(currentJsonID, newJsonID);
var final = _.difference(union, _.difference( currentJsonID, intersection);
Expected Final Outcome:
[
{
"id": "12",
"property1Name": "1"
"status": "inactive"
},
{
"id": "11",
"property1Name": "1"
"status": "inactive"
},
{
"id": "10",
"property1Name": "1"
"status": "inactive"
},
{
"id": "9",
"property1Name": "1"
"status": "active"
}
]
A solution in plain Javascript with two loops and a hash table for lookup.
function update(newArray, currentArray) {
var hash = Object.create(null);
currentArray.forEach(function (a) {
hash[a.id] = a.status;
});
newArray.forEach(function (a) {
a.status = hash[a.id] || 'inactive';
});
}
var newJson = [{ "id": "12", "property1Name": "1" }, { "id": "11", "property1Name": "1" }, { "id": "10", "property1Name": "1" }, { "id": "9", "property1Name": "1" }],
currentJson = [{ "id": "10", "property1Name": "1", "status": "inactive" }, { "id": "9", "property1Name": "1", "status": "active" }, { "id": "8", "property1Name": "1", "status": "active" }, { "id": "7", "property1Name": "1", "status": "inactive" }];
update(newJson, currentJson);
document.write('<pre>' + JSON.stringify(newJson, 0, 4) + '</pre>');

How to loop through properties of a JSON object?

I am trying to loop through the properties of JSON object, but unable to do so.
var ds={
"Table": [
{
"SrNo": 1,
"AuctionName": "test auction",
"AuctionDescription": "auction desc",
"Testproject": "Y",
"State": "India",
"City": "2",
"CompanyName": "IIFL",
"Commodity": "10001",
"BaseLineSpend": "50000",
"ContractMonths": "5",
"Owner": "arbaaz",
"PreviewBids": "Y",
"PrebidEndTime": "2015-09-11T18:00:00",
"BiddingStartTime": "2015-09-10T18:00:00",
"FirstTimeRunTime": 10,
"TimeBtwLotClosing": 15,
"BidRank": "20",
"StartOverTime": 25,
"OverTime": 30,
"Buffer": "Y",
"ImproveBidBy": "PERCENTAGE",
"TieBids": "Y",
"ActiveObservers": "Babitha G-C140492,",
"Observers": "Tabrez Abdul Aziz Shaikh-A185615,",
"ProjectOwner": "Tahir - Siddiqui-C107037,Tahir Ali-C132420,",
"Administrator": "Rabi Roy-V182597,Gagan Kondalana Poonacha-C134452,Rabindra Kumar Choubey-C139454,",
"GUID": "200869b0-e6be-4642-95ec-97509e457d63",
"MkrId": "C123627",
"MkrDt": "2015-09-03T16:23:15.917",
"IsCreated": null
}
]
}
Based on other similar question on stackoverflow. I tried:
var DataSet = jQuery.parseJSON(ds);
var json_parsed = DataSet.Table;
var items = json_parsed.Items; // this is always undefined in console.
for (var i = 0; i < items.length; ++i) {
console.log("Item #" + i);
for (var name in items[i]) {
alert(name + "=" + items[i][name]);
}
}
I get undefined at json_parsed.Items; in console.
I am expecting property names to be displayed in alert eg: Srno, AuctionName .. so on.
Well, Table is an array, for a start. Second, even if you used Table[0].Items, there's no Items property, which is why you're getting "undefined".
So try this instead:
var items = json_parsed[0];
for (var name in items) {
alert(name + "=" + items[name]);
}
DEMO
I see you have jQuery in there. The Javascript approach is good. But if you want to loop through a JSON object in jQuery, then you can try following code:
var ds={
"Table": [
{
"SrNo": 1,
"AuctionName": "test auction",
"AuctionDescription": "auction desc",
"Testproject": "Y",
"State": "India",
"City": "2",
"CompanyName": "IIFL",
"Commodity": "10001",
"BaseLineSpend": "50000",
"ContractMonths": "5",
"Owner": "arbaaz",
"PreviewBids": "Y",
"PrebidEndTime": "2015-09-11T18:00:00",
"BiddingStartTime": "2015-09-10T18:00:00",
"FirstTimeRunTime": 10,
"TimeBtwLotClosing": 15,
"BidRank": "20",
"StartOverTime": 25,
"OverTime": 30,
"Buffer": "Y",
"ImproveBidBy": "PERCENTAGE",
"TieBids": "Y",
"ActiveObservers": "Babitha G-C140492,",
"Observers": "Tabrez Abdul Aziz Shaikh-A185615,",
"ProjectOwner": "Tahir - Siddiqui-C107037,Tahir Ali-C132420,",
"Administrator": "Rabi Roy-V182597,Gagan Kondalana Poonacha-C134452,Rabindra Kumar Choubey-C139454,",
"GUID": "200869b0-e6be-4642-95ec-97509e457d63",
"MkrId": "C123627",
"MkrDt": "2015-09-03T16:23:15.917",
"IsCreated": null
}
]
}
var jsonData = ds.Table[0];
$.each(jsonData, function(index, value) {
console.log( index + '=' + value);
});

Creating a JSON object from a Multidimensional Javascript Array in the correct format for submission to Rails

Hi Guys I’m trying to create a javascript multidimensional array as seen below.
$('#rfp_import_table > tbody > tr').each(function(row) {
TableData[row] = {
"sheet_name": $('#sheet_name_' + i).text(),
"last_row": $('#sheet_last_row_' + i).text(),
"sheet_id": $('#sheet_id_' + i).text(),
"sheet_import": $('#sheet_import_' + i).is(':checked'),
"sheet_import_column": $('#sheet_import_column_' + i).val()
}
i++;
});
TableData = $.toJSON(TableData);
This is creating an array that looks like
[
{
"sheet_name": "Offeror Instructions",
"last_row": "99",
"sheet_id": "0",
"sheet_import": true,
"sheet_import_column": "C"
},
{
"sheet_name": "S3 SAI_Availability_Scale",
"last_row": "22",
"sheet_id": "38",
"sheet_import": true,
"sheet_import_column": "C"
},
{
"sheet_name": "S4 SAI_Deploy_and_Admin",
"last_row": "21",
"sheet_id": "39",
"sheet_import": true,
"sheet_import_column": "C"
}
]
I need an array that can be submitted to rails (using ajax $ jquery not form_for..). I beleive the format I need is
[“sheets”:
{
"sheet_name": "Offeror Instructions",
"last_row": "99",
"sheet_id": "0",
"sheet_import": true,
"sheet_import_column": "C"
},
{
"sheet_name": "S3 SAI_Availability_Scale",
"last_row": "22",
"sheet_id": "38",
"sheet_import": true,
"sheet_import_column": "C"
},
{
"sheet_name": "S4 SAI_Deploy_and_Admin",
"last_row": "21",
"sheet_id": "39",
"sheet_import": true,
"sheet_import_column": "C"
}
]
What would be the correct way to modify my javascript to produce the correct format?
Thanks in advance.
var sampleObj1 = {
"a": {
"id": "1",
"gravatar": "03ce78e04102c67d6144"
},
"b": {
"id": "1",
"name": 'asd'
},
"c": {
"id": "1702c3d0-df12-2d1b",
"name": "Jeff"
}
};
var sampleTestArr = Object.keys(sampleObj1).map(function(data){
return sampleObj1[data];
});

Categories