What's wrong with this bubble-sort function? - javascript

I have my array defined but at the moment i go into implement my bubble sorting function it doesn't enter the first for loop. It does run the function however
function bubbleSort (){
for (var j=0; j++; j < valores.length){
for (var i=j+1; i++; i < valores.length){
if (valores[j]>valores[i]){
var temp=0
temp=valores[j]
valores[i]=valores[j]
valores[j]=temp
}
}
}
console.log(valores)
}
so if valores input [2,1] I expect the output in console log to be [1,2].
I obtain my array by this function if that is of any help:
let valores =[];
let papelero=10;
function agregarValor (){
if (valores.length < papelero){
let val = Number(valor.value)
valores.push(val)
console.log(valores)
}
}

like #ug_ said my swap was incorrect, and he previously said j and i were incremented in the wrong places.
function bubbleSort() {
for (var j=0; j<valores.length; j++) {
for (var i=j+1; i<valores.length; i++) {
if (valores[j]>valores[i]) {
var temp=0
temp=valores[i]
valores[i]=valores[j]
valores[j]=temp
}
}
}
console.log(valores)
}

Related

Access array outside for loop

I want to access array variable outside the loop. but its returning null. below is sample code.
var result = [];
for (var i=0; i < 10; i++) {
result.push[i];
}
The syntex of push method is push() not push[].
var result = [];
for (var i=0; i < 10; i++) {
result.push(i);
}
console.log(result);
For more info about push() look How to append something to an array?
push is a method implemented on array. The basic syntax of invoking or calling a function is to specify parenthesis () after the function name.
Array.prototype.push()
The push() method adds one or more elements to the end of an array and returns the new length of the array.
var result = [];
for (var i=0; i < 10; i++) {
result.push(i);
}
console.log(result);
Please use the below code:
var result = [];
for (var i=0; i < 10; i++) {
result.push(i);
}
You can do that like this also.
var result = [];
for (var i=0; i < 10; i++) {
result[i]=i;
}
If you want to use push then use like this result.push(i)

How to check duplicate entries while adding to javascript object dynamically?

I have this AngularJS service.
demoService.getDemoData($scope.countEP).then(function (data) {
console.log(data);
for (var i = 0; i < data.length; i++) {
$scope.allEditorPicks.push(data[i]);
}
});
In this case,allEditorPicks is an array i have defined at the top of the code as follows.
$scope.allEditorPicks = [];
Here's the problem, when I'm using this array and printing these data, the array has same items. Duplicating. So I need a way to check existing items and stop adding them in that allEditorPicks array. We need to do this inside the for loop. I tried adding another loop inside the for loop and read the allEditorPicks array and check. But that doesn't work too.
demoService.getDemoData($scope.countEP).then(function (data) {
console.log(data);
for (var i = 0; i < data.length; i++) {
for (var j = 0; j < $scope.allEditorPicks.length; j++) {
if ($scope.allEditorPicks[j].itemName == data[i].itemName) {
console.log("Item Exists")
} else {
$scope.allEditorPicks.push(data[i]);
}
}
}
});
This is the solution I tried. My browser got freezes and stopped working when I run this code. Please give me a solution.
first, sort the array by itemName and then remove the duplicates according to the order.
data = data.sort(function(a,b){
return a.itemName - b.itemName;
});
for (var i = 0; i < data.length; i++) {
if(data[i].itemName === data[i++].itemName){
console.log("Item Exists");
}else {
$scope.allEditorPicks.push(data[i]);
}
}
Try this :
demoService.getDemoData($scope.countEP).then(function (data) {
for(let i = 0; i < data.length; i++){
let found = $scope.allEditorPicks.find(elt => {
return elt.itemName === data[i].itemName;
});
if(!found){
$scope.allEditorPicks.push(data[i]);
}
}
})

Creating a global function that withholds for loops

How do I create a for loop that can be used in other functions?
How do I create a global variable with for loops?
arrayNr1 = [4,8,13,2]
arrayNr2 = [1,2,3,13]
function globalLoop(array1, array2) {
for(var i=0; i<array1.length; i++) {
for(var j=0; j<array2.length; j++){
if(array1[i] == array2[j]) {
return array2[j]
}
}
}
}
console.log(globalLoop(arrayNr1,arrayNr2)); //-> 13
Why is it only returning 13 instead of 13 and 2?
The first time the if statement is true, the function will return.
The loop won't keep going and return more things.
A function can only return a single thing, and a return statement will stop the function from running further.
If you want to find every match, then you need to store matches somewhere (such as another array) and return after the loops have finished.
Check it:
arrayNr1 = [4,8,13,2];
arrayNr2 = [1,2,3,13];
arrayFinal = [];
function globalLoop(array1, array2) {
for(var i=0; i<array1.length; i++) {
for(var j=0; j<array2.length; j++){
if(array1[i] == array2[j]) {
arrayFinal.push(array2[j])
}
}
}
}
globalLoop(arrayNr1,arrayNr2);
console.log(arrayFinal);
You exit the function at the first find.
return array2[j]
You could collect the values with an array.
function globalLoop(array1, array2) {
var result = [], i, j;
for (i = 0; i < array1.length; i++) {
for (j = 0; j < array2.length; j++){
if (array1[i] == array2[j]) {
result.push(array1[i]);
break;
}
}
}
return result;
}
var arrayNr1 = [4, 8, 13, 2],
arrayNr2 = [1, 2, 3, 13];
console.log(globalLoop(arrayNr1,arrayNr2));
You are iterating over arrayNr1 first and the first match in both arrays is (13, 13). The return statement stops the loop on the first match, it never gets to the second.
The following snippet collects all matches and returns an array.
arrayNr1 = [4,8,13,2]
arrayNr2 = [1,2,3,13]
function globalLoop(array1, array2) {
var equal_elements = [];
for(var i=0; i<array1.length; i++) {
for(var j=0; j<array2.length; j++){
if(array1[i] == array2[j]) {
// collect matches
equal_elements.push(array2[j]);
}
}
}
return equal_elements;
}
console.log(globalLoop(arrayNr1,arrayNr2));

Find if Array contains a user

I have a parse background job that contains a simple query.each for one class. This class has 2 Arrays field filled with objects.IDs. Inside this query, for every single object, i need to check if the objects.ID of the first Array are contained in the second Array.
Basically in a simple loop:
var j = 0;
for (var j = 0; j < firstArray.length; j++) {
if(firstArray[j] "isContainedIn" secondArray){
// my custom code
}
}
What i can't figure out is the function to use, if exist..Does javascript have a function like that or i need to make a nested loop to achieve my goal?
EDIT: i worked it out using indexOf but the solution proposed by Shqiptar didn't work so here is the one that actually works:
first Array name = usersEligibleToVote
second Array name = usersThatVoted
for (var j = 0; j < usersEligibleToVote.length; j++) {
if(usersThatVoted.indexOf(usersEligibleToVote[j]) === -1){
console.log("user.id "+usersEligibleToVote[j]+" needs to vote");
} else {
console.log("user.id "+usersEligibleToVote[j]+" has voted");
}
}
var j = 0;
for (var j = 0; j < firstArray.length; j++) {
if(firstArray[j].contains(secondArray))
{
// your custom code here
}
}
And then for checking if an object is the same :
var j = 0;
for (var j = 0; j < firstArray.length; j++) {
if(firstArray[j].indexOf(secondArray) != -1)
{
// your custom code here
}
}
I would process it through a simple jQuery and javascript for loop like so:
var arr1;
var arr2;
var i;
for(i = 0; i < arr1.length; i++) {
if ($.inArray(arr1[i], arr2) {
break; //do things here or what not
}
}

loop on Multiple array values

I am confused about how to iterate on multiple values.
for example : values.categories[0].num[0].entry[0].label;
Do I need to write three for loops in order to iterate through categories, num and entry.
Because categories[0] will always identify the 1st position, but am looking for generic categories[i].
Can you please help me out whether to write three for loops or better option is there to achieve.?
This is what I have tried:
var result = [];
for (var i = 0; i < categories.length; i++) {
var abc = categories[i].num;
for (var j = 0; j < abc.length; j++){
var def = num[i].entry;
}
for(var k = 0; k < def.length; k++){
var ghi = entry[i].label;
result.push(ghi)
console.log(result);
}
}
you can use the each function of jquery.
$.each(categories, function(ci, num) {
// This set the index of the array in ci and the value in num = categories[ci]
$.each(num, function(ni, entry) {
// etc ...
});
});
if you want it to stop the iteration you can return false inside the callback function.

Categories

Resources