Take a number in ascending order - javascript

I have this code where it takes numbers randomly from an array, but I would like it to take numbers in ascending order like 1 2 3 4 and not at random, could someone help?
jQuery(function( $ ){
function setNumerosAleatorios(qtde) {
if (qtde > ) {
const shuffleArray = array => {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.min() * (i;));
const temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
// Definindo nĂºmeros aleatorios
let aleatorios = appRifaObj.numeros.filter(v => v.status === 3);
shuffleArray(aleatorios);
aleatorios = aleatorios
.slice(0, qtde)
.map(v => v.numero);
setEscolhidos(aleatorios);
}
}
function setEscolhidos(numeros) {
//console.log(numeros)
appRifaObj.escolhidos.forEach(v => v.selected = false);
numeros
.forEach(numero => {
let existe = appRifaObj.numeros.find(v => v.numero == numero);
if (existe) {
existe.status = 3;
existe.selected = true;
}
});
updateEscolhidos();
}
qtd = 1
$( "div.app-compra-automatica .increment" ).click(function() {
qtd>0 ? qtd -- : null
$( "div.app-compra-automatica input.qtd" ).val(qtd)
});
$( "div.app-compra-automatica .decrement" ).click(function() {
qtd ++
$( "div.app-compra-automatica input.qtd" ).val(qtd)
});
$( "div.app-compra-automatica button.comprar" ).click(function() {
qtd = $( "div.app-compra-automatica input.qtd" ).val()
setNumerosAleatorios(qtd)
});
});

Related

Javascript Push is overwriting the previous elements

I am trying render the plotly.js graph,
For some reason though, the traces.push(this.getTrace(val, calAdjustData)) part seems to be overwriting previous data in the traces array, For every iteration it is returns single value, but finally last value is overwriting all previous values.
destArray.forEach(val=> {
traces.push(this.getTrace(val, calAdjustData));
});
getTrace() function is
getTrace(trace:any, data:any) {
let appConfig: any = [];
appConfig['TABLES'] = {
'R_FORMAT': ',d',
'MONTH_BEGIN_DATE_KEY': 'MONTH_BEGIN_DT',
'CAST_KEYS': [
'DOLLARS_ACTUAL', 'DOLLARS_FORECAST', 'DOLLARS_CALC_FORECAST',
'PY_DOLLARS_ACTUAL', 'PY_DOLLARS_FORECAST', 'PY_DOLLARS_CALC_FORECAST',
'DOLLARS_SUBMITTED', 'PY_DOLLARS_SUBMITTED',
'DOLLARS_ADJ', 'PY_DOLLARS_ADJ',
'DOLLARS_BUDGET', 'NEWNESS_FLAG'
]
};
var traceTmpl:any = Object.assign(this.graphConfig.graphSettings.traceTmpl);
if ("color" in trace) traceTmpl.line.color = trace.color;
if ("dash" in trace) traceTmpl.line.dash = trace.dash;
//traceTmpl.visible = "legendonly";
if ( trace[ "legendgroup" ] ) traceTmpl.legendgroup = trace.legendgroup;
// Compile the trace name for legened and display
traceTmpl.name = trace.label.replace("{type}", this.graphConfig.display.typeLabelMap[this.displaySettings.type]);
traceTmpl.label = trace.label;
if (!(localStorage['legendItems'] =='')) {
let tempArray = JSON.parse(localStorage['legendItems']).filter((x:any)=>x.name.replace("{type}",this.graphConfig.display.typeLabelMap[this.displaySettings.type]) == traceTmpl.name);
if(tempArray && tempArray.length){
traceTmpl.visible = "legendonly"
}
}
// Compile the field name to pluck out of the data array
var field = trace.field.replace("{cal}", this.displaySettings.cal).replace("{type}", this.displaySettings.type);
// Prepare the trace data
traceTmpl.x = _.map(data, appConfig.TABLES.MONTH_BEGIN_DATE_KEY );
traceTmpl.y = _.map(data, field);
// todo: refactor into a function
var tempDate = new Date();
var currentDate = this.getDate( this.displaySettings.currentMonth || [ tempDate.getUTCFullYear(), ( tempDate.getUTCMonth() > 8 ? '':'0' ) + ( tempDate.getUTCMonth() + 1 ), '01' ].join('-') );
if( trace.name.endsWith('actuals') || trace.name.endsWith('actuals_LY') ){
var lastIdx = -1;
traceTmpl.y.forEach( function( val:any, idx:any ) {
if ( val !== 0 ) lastIdx = idx;
} );
for ( let idx = lastIdx + 1; idx < traceTmpl.y.length; ++idx ) traceTmpl.y[ idx ] = void 0;
} else if ( trace.name.endsWith('work_plan')){
var firstIdx = -1;
traceTmpl.y.forEach((val : any, idx :any) => {
var monthCheck = this.getDate( data[idx][ appConfig.TABLES.MONTH_BEGIN_DATE_KEY ] ).getMonth() > currentDate.getMonth();
var yearCheck = this.getDate( data[idx][ appConfig.TABLES.MONTH_BEGIN_DATE_KEY ] ).getUTCFullYear() >= currentDate.getUTCFullYear();
if ( val !== 0 && firstIdx === -1 && ( ( yearCheck && monthCheck ) || this.getDate( data[idx][ appConfig.TABLES.MONTH_BEGIN_DATE_KEY ] ).getUTCFullYear() > currentDate.getUTCFullYear() ) ) {
firstIdx = idx;
}
})
if ( firstIdx !== -1 ){
for ( let idx = 0; idx < firstIdx; ++idx ) traceTmpl.y[idx] = void 0;
}
if ( firstIdx > 0 && trace.altField ){
var altField = trace.altField.replace("{cal}", this.displaySettings.cal).replace("{type}", this.displaySettings.type);
traceTmpl.y[ firstIdx - 1 ] = data[ firstIdx - 1 ][ altField ];
}
} else if ( trace.name == "inventory.forecast" ){
traceTmpl.y.forEach( function ( val:any, idx:any, array:any ) {
if ( val ){
array[ idx ] = val > 0 ? val:0;
}
} );
}
//convert to K dollars as plotly doesn't support that format
//Convert from string to numbers (temporary as DB2 returning strings for some reason) and then convert to K dollars or Units
var denominator = 1000; // K Dollars
if (this.displaySettings.type === "UNITS") denominator = 1;
for (let i in traceTmpl.y) traceTmpl.y[i] = ((+traceTmpl.y[i]) / denominator);
var formatter = d3.format( ( this.displaySettings.type === "DOLLARS" ? '$':'' ) + appConfig.TABLES.R_FORMAT );
traceTmpl.text = traceTmpl.y.map( function ( d:any ){
} );
traceTmpl.text = traceTmpl.y.map((d : any) => {
if ( d || d === 0 ){
return formatter( Math.ceil( d ) );
}else{
return undefined;
}
});
return traceTmpl;
};
Please suggest any solution for this issue, already few similar questions here, but nothing worked for me.

Select2 in v3.x and v4.x

The code below works with select2 Version: 3.X but when I use "https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.full.min.js" and "https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.min.css" it does not add the values:
var data = [];
for(var i = 0; i < 10000; i++){
data.push({id: ""+i, text: ""+i});
}
$("input").select2({
initSelection: function(element, callback) {
var selection = _.find(data, function(metric){
return metric.id === element.val();
})
callback(selection);
},
query: function(options){
var pageSize = 100;
var startIndex = (options.page - 1) * pageSize;
var filteredData = data;
if( options.term && options.term.length > 0 ){
if( !options.context ){
var term = options.term.toLowerCase();
options.context = data.filter( function(metric){
return ( metric.text.toLowerCase().indexOf(term) !== -1 );
});
}
filteredData = options.context;
}
options.callback({
context: filteredData,
results: filteredData.slice(startIndex, startIndex + pageSize),
more: (startIndex + pageSize) < filteredData.length
});
},
placeholder: "Select a metric"
});
here is the link of jsfiddle:
http://jsfiddle.net/Z7bDG/1/

Algorithm to layout events with maximum width with JavaScript

Not long ago I found this question that relates to the problem I am trying to solve: Visualization of calendar events. Algorithm to layout events with maximum width
I look at some of the examples that were created and I saw that it did not take the full width in certain circumstances.
The bottom rectangles should be full width (http://jsfiddle.net/q4nkpL4r/).
$( document ).ready( function( ) {
var column_index = 0;
$( '#timesheet-events .daysheet-container' ).each( function() {
var block_width = $(this).width();
var columns = [];
var lastEventEnding = null;
// Create an array of all events
var events = $('.bubble_selector', this).map(function(index, o) {
o = $(o);
var top = o.offset().top;
return {
'obj': o,
'top': top,
'bottom': top + o.height()
};
}).get();
// Sort it by starting time, and then by ending time.
events = events.sort(function(e1,e2) {
if (e1.top < e2.top) return -1;
if (e1.top > e2.top) return 1;
if (e1.bottom < e2.bottom) return -1;
if (e1.bottom > e2.bottom) return 1;
return 0;
});
// Iterate over the sorted array
$(events).each(function(index, e) {
if (lastEventEnding !== null && e.top >= lastEventEnding) {
PackEvents( columns, block_width );
columns = [];
lastEventEnding = null;
}
var placed = false;
for (var i = 0; i < columns.length; i++) {
var col = columns[ i ];
if (!collidesWith( col[col.length-1], e ) ) {
col.push(e);
placed = true;
break;
}
}
if (!placed) {
columns.push([e]);
}
if (lastEventEnding === null || e.bottom > lastEventEnding) {
lastEventEnding = e.bottom;
}
});
if (columns.length > 0) {
PackEvents( columns, block_width );
}
});
});
function PackEvents( columns, block_width )
{
var n = columns.length;
for (var i = 0; i < n; i++) {
var col = columns[ i ];
for (var j = 0; j < col.length; j++)
{
var bubble = col[j];
bubble.obj.css( 'left', (i / n)*100 + '%' );
bubble.obj.css( 'width', block_width/n - 1 );
}
}
}
function collidesWith( a, b )
{
return a.bottom > b.top && a.top < b.bottom;
}
I tried to change the code but with no success. How do I make the elements take full width and not just fit in the column?

pairing object items together with a loop

I have the following data and I am wondering how I can match up email1 to password1 and email2 to password2 in this format email:password. I can do it if I do object[0] +":"+ object[1] and object[2] +":"+ object[3] but when the object gets populated with 10 or more items this method is not very efficient. How can I do this with a loop?
I'm using the following code to create the structure:
$("#accounts").on("submit", function(event) {
event.preventDefault();
var form = $(this).serializeArray();
});
You can change the increment in a for loop. Try:
var results = [];
For(var i = 0; i < vals.length; i += 2) {
results.push( { vals[i].value: vals[i+1].value });
}
You can try increment your loop step.
Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Statements?redirectlocale=en-US&redirectslug=JavaScript%2FGuide%2FStatements#for_Statement
Code:
var testMe=new Array({"name":"em1"},{"pwd":"pwd1"},{"name":"em2"},{"pwd":"em2"});
console.log(testMe)
for (var i = 0; i < testMe.length; i+=2) {
console.log(testMe[i].name+"-->"+testMe[i+1].pwd)
}
Demo: http://jsfiddle.net/IrvinDominin/qbVwH/
//
Array.prototype.e = Array.prototype.forEach;
function pair( arr ) {
var len = arr.length;
if ( len ) {
do {
arr.push( arr.splice( 0, 2 ) );
} while ( ( len -= 2 ) >= 2 );
}
return arr;
};
var yourData = [
{ name:"email1", value:"321" },
{ name:"pw1", value:"123" },
{ name:"email2", value:"qwe" },
{ name:"pw2", value:"ewq" },
{ name:"email3", value:"234" },
{ name:"pw3", value:"432" }
],
pairs = {};
pair( yourData )
.e(
function ( P ) {
pairs[ P[0].name ] = P[1].name;
}
);
console.log( pairs );
// Object { email1="pw1", email2="pw2", email3="pw4"}
//

Removing duplicates from FOR statement in Javascript?

I have the following
var ahrefLength = $('a').length;
for (var i = 0; i < ahrefLength; i++) {
var ahrefUrl = $('a')[i].attr('href');
if(ahrefUrl != '') {
$('a')[i].text('Unique');
}
}
How can I fix this so that no duplicates of "href" appear ? At the moment, if 2 href are the same it fixes both ? i.e. I need to ensure that no duplicates
var list = {};
$('a[href]').text(function(i,text) {
var href = $(this).attr('href');
if( !(href in list) )
return list[href] = 'Unique';
else
; // what do you want to do with the duplicate?
});
To use a for statement:
var list = {};
var a_els = $('a[href]'); // Cache the DOM selection
var len = a_els.length;
for(var i = 0; i < len; i++) {
var a_i = a_els.eq(i);
var href = a_i.attr('href');
if( !(href in list) )
a_i.text(list[href] = 'Unique');
else
; // what do you want to do with the duplicate?
}
You can use an associative array (viz., an object) as a sort of "set" to keep track of what URLs you've already seen:
var ahrefLength = $('a').length;
var hrefsToSkip = { '': true };
for (var i = 0; i < ahrefLength; i++) {
var ahrefUrl = $('a')[i].attr('href');
if(! hrefsToSkip[ahrefUrl]) {
$('a')[i].text('Unique');
hrefsToSkip[ahrefUrl] = true;
}
}
var hrefIdx = {};
var href = null;
$('a').each(function(i, e) {
href = $(this).attr('href');
if ( href != '' && !hrefIdx[href]) {
$(this).text('Unique');
hrefIdx[href] = true;
}
});
Use jQuery slice:)
Demo: http://jsfiddle.net/mhNra/
Remove all duplicates starting from the end
$( "a" ).each( function() {
$( "a[href=" + $( this ).attr( "href" ) + "]" ).slice( 0, -1 ).remove()
});
Remove all duplicates starting from the first anchor
$( "a" ).each( function() {
var arr = $( "a[href=" + $( this ).attr( "href" ) + "]" );
arr.slice( 1, arr.length ).remove()
});

Categories

Resources