I'm trying to create subsets of an Array in a recurring manner. I've an Array in the form of [0,1,2,3,4,5,6]. I'd like to create subsets like [0,1,2], [1,2,3],[2,3,4],[3,4,5],[4,5,6],[5,6,0],[6,0,1],[0,1,2] and so on. But, its not breaking after [4,5,6].
Here is my code
var app = angular.module('app',[]);
app.controller('EventController',function EventController($scope) {
$scope.count = 0;
var arr = [], subArr = [], currentIndex;
for(var i = 0; i < 7; i++) {
arr.push(i)
}
$scope.next = function() {
currentIndex = $scope.count;
subArr = [];
$scope.count++;
subArr.push(currentIndex);
subArr.push(currentIndex+1);
subArr.push(currentIndex+2);
if(arr.indexOf(currentIndex+1) == -1) {
console.log(currentIndex+1,'Element not available');
$scope.count = 0;
currentIndex = $scope.count
}
console.log(subArr);
}
});
Here is the fiddle
Any ideas would be greatly appreciated.
Try this:
var app = angular.module('app',[]);
app.controller('EventController',function EventController($scope) {
$scope.count = 0;
var subArr = [], currentIndex;
$scope.arr = [];
for(var i = 0; i < 7; i++) {
$scope.arr.push(i);
}
$scope.next = function() {
currentIndex = $scope.count;
//console.log(currentIndex);
subArr = [];
$scope.count++;
subArr.push(currentIndex);
if($scope.arr.indexOf(currentIndex) == $scope.arr.length -2) {
console.log(currentIndex+2,'Element not available');
subArr.push(currentIndex+1);
$scope.count = 0;
subArr.push($scope.arr[0]);
}
else if($scope.arr.indexOf(currentIndex) == $scope.arr.length -1) {
console.log(currentIndex+1,'Element not available');
subArr.push($scope.arr[0]);
subArr.push($scope.arr[1]);
currentIndex = $scope.count;
}
else{
subArr.push(currentIndex+1);
subArr.push(currentIndex+2);
}
console.log(subArr);
}
});
The problem is, you are pushing elements before if condition.
1. Move the if block before pushing data to array
2. Change arr.indexOf(currentIndex+1) == -1 to arr.indexOf(currentIndex+2) == -1
var app = angular.module('app',[]);
app.controller('EventController',function EventController($scope) {
$scope.count = 0;
var arr = [], subArr = [], currentIndex;
for(var i = 0; i < 7; i++) {
arr.push(i)
}
$scope.next = function() {
currentIndex = $scope.count;
//console.log(currentIndex);
subArr = [];
$scope.count++;
subArr.push((currentIndex)%arr.length);
subArr.push((currentIndex+1)%arr.length);
subArr.push((currentIndex+2)%arr.length);
console.log(subArr);
}
});
I guess the below code will help. It is self explanatory.
function createSubset (array, subsetSize, subsets){
var inputArray = array,
subset,
subsetCollection = [],
noOfSubsets = subsets || inputArray.length + 1,
size = subsetSize,
current = 0,
i;
while (noOfSubsets--) {
subset = [];
for (i = 0; i < size; i++) {
subset.push( inputArray[ (current + i) % inputArray.length] );
}
current += 1 ;
subsetCollection.push(subset);
}
return subsetCollection;
}
console.log('Test Case start');
var a = [0,1,2,3,4,5,6],
result = createSubset(a, 3);
console.log(result);
console.log('Test Case end');
console.log('Test Case start');
var a = [0,1,2,3,4,5,6],
result = createSubset(a, 3, 4);
console.log(result);
console.log('Test Case end');
Related
*** i am try to this count two string match character ***
var s1 = "abcd";
var s2 = "aad";
function match(s1,s2){
var obj = {}
var spilt1 = s1.split("")
var spilt2 = s2.split("")
for(let i =0;i<spilt1.length;i++){
let th = spilt2.includes(spilt1[i])
if(!obj[th[i]]){
obj[th[i]] = 0
}else{
obj[th[i]]++
}
}
return obj
}
console.log(match(s1,s2))
*** output like this ***
{
a:1,
d:1
}
function match(str1, str2) {
const str1Obj = {};
const resultObj = {};
for (let i = 0; i < str1.length; i++) {
str1Obj[str1[i]] = str1Obj.hasOwnProperty(str1[i])
? str1Obj[str1[i]] + 1
: 1;
}
for (let i = 0; i < str2.length; i++) {
if (str1Obj.hasOwnProperty(str2[i]) && str1Obj[str2[i]] >= 1) {
resultObj[str2[i]] = resultObj.hasOwnProperty(str2[i])
? resultObj[str2[i]] + 1
: 1;
str1Obj[str2[i]] -= 1;
}
}
return resultObj;
}
I am trying to push elements to an array in a nested loop, but only the last item is getting repeated in the final array, where am I going wrong, very new to javascript asynchronous concept.Below is the function in which I push the items to an array.
$scope.showBeList = function(feed) {
if (feed[srcServ.KEY_CONTENT_TEXT]) {
var content = JSON.parse(feed[srcServ.KEY_CONTENT_TEXT])
if (content) {
$scope.beList = {};
for (var key in content) {
var decorationVal;
//reading value from a lokijs collection
var decoration = dataServ[srcServ.CONST_COLLECTION_DECORATION].find({
'name': key
});
if (decoration && decoration.length) {
decorationVal = decoration[0];
if (decorationVal != null) {
var tempObj = JSON.parse(decorationVal.value);
if (tempObj) {
var header = tempObj[key][key + '_HEADER'];
if (header) {
var counter = content[key].length;
var tempItems = [];
for (var j = 0; j < content[key].length; j++) {
(function(j) {
var obj = {};
obj[srcServ.KEY_MAIN_HEADER] = tempObj[key][srcServ.KEY_DESC];
obj[srcServ.KEY_SUB_HEADER] = header[srcServ.KEY_DESC];
obj.id = j;
var itemVal = content[key][j][key + '_HEADER'];
var details = [];
var notes = [];
for (var item in itemVal) {
var val = null;
var found = false;
for (var i = 0; i < header.field.length; i++) {
if (header.field[i].name == item) {
val = header.field[i];
found = true;
break;
}
}
if (found && val != null) {
val[srcServ.KEY_DESC_VALUE] = itemVal[item];
details.push(val);
}
}
obj.details = details;
counter--;
if (counter == 0) {
$scope.showMoreDetails = true;
$scope.beList.beItems = tempItems;
console.log(JSON.stringify($scope.beList));
}
tempItems.push(obj)
})(j);
// $scope.beList.beItems.push(obj);
}
}
}
}
}
}
}
}
}
I have a problem with this pagination code. I have 1 button instead of 3. Can you help?
paginator.js
$scope.generateButtons = function () {
var buttons = [],
pageCount = getPageCount(),
buttonCount;
console.log("page " + pageCount);
buttonCount = pageCount > 2 ? 3 : pageCount;
for (var i = 0; i < buttonCount; i++) {
var index = +$scope.offset + i -1;
if (index > 0) {
buttons.push(index);
}
};
return buttons;
};
View in plunker
My suggestion is to use Angular UI bootstrap pagination, and not write it from scratch https://angular-ui.github.io/bootstrap/#/pagination
angular.module('ui.bootstrap.demo').controller('PaginationDemoCtrl', function ($scope, $log) {
$scope.totalItems = 64;
$scope.currentPage = 4;
$scope.setPage = function (pageNo) {
$scope.currentPage = pageNo;
};
$scope.pageChanged = function() {
$log.log('Page changed to: ' + $scope.currentPage);
};
$scope.maxSize = 5;
$scope.bigTotalItems = 175;
$scope.bigCurrentPage = 1;
});
It's really not about angular related problem. Its all about the logic for $scope.generateButtons = function () {...} Please change your logic as you need. Here is your code (edited) for displaying 3 buttons.
$scope.generateButtons = function () {
var buttons = [],
pageCount = getPageCount(),
buttonCount;
buttonCount = pageCount > 2 ? 3 : pageCount;
for (var i = 0; i < buttonCount; i++) {
var index = parseInt($scope.offset) + i+1;
if (index >= 0) { // this `if` is not really needed
buttons.push(index);
}
};
return buttons;
};
Enjoy!
Need help with the chaining. The functions work. But async calls make it hard for me to get everything. Help me think right!
My thought:
Get All Webs recursively (function works)
Get all lists from webs and iff announcementlist add to array and pass along
Get two items from all announcmentlists and sort by created.
Add ALL announcement items into one large array (to be able to sort array later.
Heres the code,
function getAllWebs(success, error) {
var ctx = SP.ClientContext.get_current();
var web = ctx.get_site().get_rootWeb();
var result = [];
var level = 0;
result.push(web);
var getAllWebsInner = function (web, result, success, error) {
level++;
var ctx = web.get_context();
var webs = web.get_webs();
ctx.load(webs, 'Include(Title,Webs,ServerRelativeUrl)');
ctx.executeQueryAsync(
function () {
for (var i = 0; i < webs.get_count() ; i++) {
var web = webs.getItemAtIndex(i);
result.push(web);
if (web.get_webs().get_count() > 0) {
getAllWebsInner(web, result, success, error);
}
}
level--;
if (level == 0 && success)
success(result);
},
error);
};
getAllWebsInner(web, result, success, error);
}
function error(sender, args) {
console.log(args.get_message());
};
function getAnnouncementLists(web, success, error) {
var dfd = $.Deferred();
var ctx = web.get_context();
var collList = web.get_lists();
var result = []
ctx.load(collList, 'Include(Title, Id, BaseTemplate)');
ctx.executeQueryAsync(function () {
for (var i = 0; i < collList.get_count() ; i++) {
var list = collList.getItemAtIndex(i);
var bTemp = list.get_baseTemplate();
if (bTemp == 104) {
result.push(list);
}
}
//success(result);
dfd.resolve(result);
}, error);
return dfd.promise();
}
function getListItems(list, success, error) {
var dfd = $.Deferred();
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><Query><OrderBy><FieldRef Name="Created" Ascending="False"></FieldRef>'
+ '</OrderBy></Query><ViewFields><FieldRef Name="Title"/><FieldRef Name="Body"/>' +
'<FieldRef Name="Created"/></ViewFields><RowLimit>2</RowLimit></View>');
var listItems = list.getItems(camlQuery);
var result = []
var ctx = list.get_parentWeb().get_context();
ctx.load(listItems);
ctx.executeQueryAsync(function () {
for (var i = 0; i < listItems.get_count() ; i++) {
var item = listItems.getItemAtIndex(i);
result.push(item);
}
dfd.resolve(result);
//success(result);
}, error);
return dfd.promise();
}
function printResults(items) {
var sortedItems = items.sort(dynamicSort("get_created()"));
alert(sortedItems);
}
function dynamicSort(property) {
var sortOrder = 1;
if (property[0] === "-") {
sortOrder = -1;
property = property.substr(1);
}
return function (a, b) {
var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
return result * sortOrder;
}
}
$(document).ready(function () {
var items = getAllWebs(
function (allwebs) {
var array = [];
for (var i = 0; i < allwebs.length; i++) {
getAnnouncementLists(allwebs[i]).then(function (announceLists) {
for (var i = 0; i < announceLists.length; i++) {
getListItems(announceLists[i]).then(function (items) {
array.push(items);
});
}
});
}
return array;
}
);
//getAllWebs(
// function (allwebs) {
// for (var i = 0; i < allwebs.length; i++) {
// getAnnouncementLists(allwebs[i],
// function (announceLists) {
// for (var i = 0; i < announceLists.length; i++) {
// getListItems(announceLists[i],
// function (items) {
// printResults(items);
// }, error);
// }
// }, error);
// }
// }, error);
});
Given the requirements to retrieve list items from Announcements lists located across site collection, below is demonstrated the modified example that contains some improvements such as:
the number of requests to the server is reduced
fixed the issue in getAllWebs function that prevents to return any results if site contains only a root web
Example
function getAllWebs(propertiesToRetrieve,success, error) {
var ctx = SP.ClientContext.get_current();
var web = ctx.get_site().get_rootWeb();
var result = [];
var level = 0;
ctx.load(web, propertiesToRetrieve);
result.push(web);
var getAllWebsInner = function (web, result, success, error) {
level++;
var ctx = web.get_context();
var webs = web.get_webs();
var includeExpr = 'Include(Webs,' + propertiesToRetrieve.join(',') + ')';
ctx.load(webs, includeExpr);
ctx.executeQueryAsync(
function () {
for (var i = 0; i < webs.get_count() ; i++) {
var web = webs.getItemAtIndex(i);
result.push(web);
if (web.get_webs().get_count() > 0) {
getAllWebsInner(web, result, success, error);
}
}
level--;
if (level == 0 && success)
success(result);
},
error);
};
getAllWebsInner(web, result, success, error);
}
function loadListItems(lists,query,success,error,results){
var results = results || [];
var curList = lists[0];
var ctx = curList.get_context();
var listItems = curList.getItems(query);
ctx.load(listItems);
ctx.executeQueryAsync(function () {
results.push.apply(results, listItems.get_data());
lists.shift();
if(lists.length > 0) {
loadListItems(lists,query,success,error,results);
}
if(lists.length == 0)
success(results);
}, error);
}
function dynamicSort(property) {
var sortOrder = 1;
if (property[0] === "-") {
sortOrder = -1;
property = property.substr(1);
}
return function (a, b) {
var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
return result * sortOrder;
}
}
var propertiesToRetrieve = ['Lists.Include(BaseTemplate)','ServerRelativeUrl'];
getAllWebs(propertiesToRetrieve,
function(allwebs){
//1. get filtered lists
var allAnnouncementLists = [];
allwebs.forEach(function(w){
var announcementLists = w.get_lists().get_data().filter(function(l){
if(l.get_baseTemplate() == SP.ListTemplateType.announcements)
return l;
});
allAnnouncementLists.push.apply(allAnnouncementLists, announcementLists);
});
//2.Load list items from lists
var query = new SP.CamlQuery(); //<-set your custom query here
loadListItems(allAnnouncementLists,query,
function(allListItems){
//3.Sort and print results
var sortedItems = allListItems.sort(dynamicSort("get_created()"));
sortedItems.forEach(function(item){
console.log(item.get_item('Title'));
});
},logError);
},
logError);
function logError(sender,args){
console.log(args.get_message());
}
I have an array like below
var colorArray = ["#a", "#b", "#c", "#d", "#e"];
From this I will generate a map like this
function initilizeColorMap(){
for(var i = 0 ;i <colorArray.length ;i++){
colorTrackingMap[i] = {value: colorArray [i],state:"unused"};
}
}
Hopw i can iterate through the map when i need a color (next color from the map ) by checking the state in javascript..?
You can have a method that will return the next color. Check out this jsfiddle : http://jsfiddle.net/QYWDb/
var colorArray = ["#a", "#b", "#c", "#d", "#e"];
var colorTrackingMap = [];
var currentIndex = -1;
for(var i = 0 ;i <colorArray.length ;i++){
colorTrackingMap[i] = {value: colorArray [i],state:"unused"};
}
function getNextColor() {
if (currentIndex > colorTrackingMap.length)
currentIndex = 0;
else
currentIndex++;
while ( colorTrackingMap[currentIndex] !== undefined &&
colorTrackingMap[currentIndex].state !== "unused" ) {
currentIndex++;
}
if ( colorTrackingMap[currentIndex] )
return colorTrackingMap[currentIndex].value;
else
return "No color available";
}
If you need color according to given index you don't have to iterate, use such code:
var currentIndex = 0;
function Next() {
var tracking = colorTrackingMap[currentIndex];
alert("color: " + tracking.value + ", state: " + tracking.state);
currentIndex++;
if (currentIndex >= colorTrackingMap.length)
currentIndex = 0;
}
Live test case.
If you mean searching the array for item with specific value, just use ordinary loop:
function Find() {
var color = document.getElementById("color").value;
var state = "";
for (var i = 0; i < colorTrackingMap.length; i++) {
if (colorTrackingMap[i].value.toLowerCase() === color) {
state = colorTrackingMap[i].state;
break;
}
}
if (state.length == 0) {
alert("color isn't mapped");
} else {
alert("state: " + state);
}
}
You can also pass the color as function argument, this is just for sake of example.
Updated test case.
You could use something like this:
var ColourMap = function (arr) {
var _map = [],
out = [],
i,
len;
// Set up the colour map straight away
for (i = 0, len = arr.length; i < len; i++) {
_map.push({
value: arr[i],
state: "unused"
});
}
return {
get_next: function () {
var i,
len,
next;
for (i = 0, len = _map.length; i < len; i++) {
if (_map[i].state === "unused") {
next = _map[i];
break;
}
}
return next;
}
}
};
And then use something like:
var m = new ColourMap(["#a", "#b", "#c", "#d", "#e"]);
m.get_next(); // get the next available element
Here's a working example.