Why does forEach return undefined? - javascript

Here is my code to solve leetcode- Two sum
let nums = [2, 7, 11, 15];
let target = 9;
for (let i = 0; i < nums.length; i++) {
let x = target - nums[i];
if (nums[i + 1] === x) {
console.log([i, i+1]) // [0, 1]
return [i, i + 1];
}
} //it ok
nums.forEach((item, index) => {
let x = target - nums[index];
if (nums[index + 1] === x) {
console.log([index, index + 1]);// [0, 1]
return [index,index+1]
}
}); // undefined
I use forEach instead of for(...), both console.log are same, but forEach returns undefined. Why?

You can use JS map
because the forEach always return undefined
let nums = [2, 7, 11, 15],
target = 9;
let m = {};
nums.map((value, index) => {
m[value] = index;
});
for (i = 0; i < nums.length; i++) {
let diff = target - nums[i];
if (m.hasOwnProperty(diff)) {
console.log(i, m[diff]);
}
}

Related

Sum of to arrays with different array sizes

I'm trying to solve sum of to array problem:
//[1,2,3] + [1,2] should be [1,3,5]
I'm able to solve this if the array are the same size, but how can I deal with different array sizes?
Here is my code for now:
function sumOfArrays(a, b) {
let result = new Array(Math.max(a.length, b.length));
let carry = 0;
for (let i = result.length - 1; i >= 0; i--) {
const elementA = a[i];
const elementB = b[i];
const additionResult = elementA + elementB + carry;
result[i] = (additionResult % 10);
carry = Math.floor(additionResult / 10);
}
}
I'm basically getting null values into the result array If there is a difference in the size of the array
You could add a comparison if the 2 arrays are the same length.
If not, you can 'pad' it from the beginning with 0's until ther are the same length.
Then your code will work as expected (after adding return result ;) )
const pad = (arr, size, fill = 0) => [ ...Array(size - arr.length).fill(0), ...arr ];
let a = [1,2,3];
let b = [1,2];
if (a.length < b.length) {
a = pad(a, b.length);
} else if (b.length < a.length) {
b = pad(b, a.length);
}
function sumOfArrays(a, b) {
let result = new Array(Math.max(a.length, b.length));
let carry = 0;
for (let i = result.length - 1; i >= 0; i--) {
const elementA = a[i];
const elementB = b[i];
const additionResult = elementA + elementB + carry;
result[i] = (additionResult % 10);
carry = Math.floor(additionResult / 10);
}
return result;
}
const res = sumOfArrays(a, b);
console.log(res)
However, since the array's are now the same length, we can simplefy the code a lot by using map() and add (+) to current value of the other array on that index:
const pad = (arr, size, fill = 0) => [ ...Array(size - arr.length).fill(0), ...arr ];
let a = [1,2,3];
let b = [1,2];
if (a.length < b.length) {
a = pad(a, b.length);
} else if (b.length < a.length) {
b = pad(b, a.length);
}
function sumOfArrays(a, b) {
return a.map((n, i) => n + b[i]);
}
const res = sumOfArrays(a, b);
console.log(res)
// [
// 1,
// 3,
// 5
// ]
You could take an offset for the index to add.
function add(a, b) {
const
length = Math.max(a.length, b.length),
offsetA = a.length - length,
offsetB = b.length - length;
return Array.from(
{ length },
(_, i) => (a[i + offsetA] || 0) + (b[i + offsetB] || 0)
);
}
console.log(...add([1, 2, 3], [1, 2])); // [1, 3, 5]
console.log(...add([1, 2, 3], [4, 5, 6]));
console.log(...add([1, 2, 3, 4], [1])); // [1, 2, 3, 5]
console.log(...add([1], [1, 2, 3, 4])); // [1, 2, 3, 5]

how to generate spiral matrix in javascript?

I am trying to generate sprial matrix in javascript.
question
Given an integer A, generate a square matrix filled with elements from 1 to A^2 in spiral order.
input : 3
[ [ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ] ]
when input is 4
[ [1, 2, 3, 4],
[12, 13, 14, 5],
[11, 16, 15, 6],
[10, 9, 8, 7] ]
my approach is to create 2d array with 0 value and after that they will fill values.
let generateMatrix = function(A) {
let arr = [], counter = 1;
for (let i = 0; i < A; i++) {
let items = []
for (let j = 0; j < A; j++) {
items.push(0)
}
arr.push(items)
}
var spiralMatrix = function(arr) {
if (arr.length > 1) {
for (let i = 0; i < arr[0].length; i++) {
arr[0][i] = counter++;
}
}
return arr
}
return spiralMatrix(arr)
}
console.log(generateMatrix(2))
You could take loops for each edges and loop until no more ranges are avaliable.
function spiral(length) {
var upper = 0,
lower = length - 1,
left = 0,
right = length - 1,
i = 0,
j = 0,
result = Array.from({ length }, _ => []),
value = 1;
while (true) {
if (upper++ > lower) break;
for (; j < right; j++) result[i][j] = value++;
if (right-- < left) break;
for (; i < lower; i++) result[i][j] = value++;
if (lower-- < upper) break;
for (; j > left; j--) result[i][j] = value++;
if (left++ > right) break;
for (; i > upper; i--) result[i][j] = value++;
}
result[i][j] = value++;
return result;
}
var target = document.getElementById('out'),
i = 10;
while (--i) target.innerHTML += spiral(i).map(a => a.map(v => v.toString().padStart(2)).join(' ')).join('\n') + '\n\n';
<pre id="out"></pre>
This bit of code should do what you are trying to.
// This is your Editor pane. Write your JavaScript hem and
// use the command line to execute commands
let generateMatrix = function(A) {
let arr = [],
counter = 1;
for (let i = 0; i < A; i++) {
let items = [];
for (let j = 0; j < A; j++) {
items.push(0);
}
arr.push(items);
}
var spiralMatrix = function(arr) {
let count = 1;
let k = 0; // starting row
let m = arr.length; // ending row
let l = 0; // starting column
let n = arr[0].length; //ending column
while (k < m && l < n) {
// top
for (var i = l; i < n; i++) {
arr[k][i] = count;
count++;
}
k++;
// right
for (var i = k; i < m; i++) {
arr[i][n - 1] = count;
count++;
}
n--;
// bottom
if (k < m) {
for (var i = n - 1; i >= l; i--) {
arr[m - 1][i] = count;
count++;
}
m--;
}
// left
if (l < n) {
for (var i = m - 1; i >= k; i--) {
arr[i][l] = count;
count++;
}
l++;
}
}
return arr;
};
return spiralMatrix(arr);
};
console.log(generateMatrix(4));
This is in some ways the reverse of an answer I gave to another question. We can recursively build this up by slicing out the first row and prepending it to the result of rotating the result of a recursive call on the remaining numbers:
const reverse = a =>
[...a] .reverse ();
const transpose = m =>
m [0] .map ((c, i) => m .map (r => r [i]))
const rotate = m =>
transpose (reverse (m))
const makeSpiral = (xs, rows) =>
xs .length < 2
? [[... xs]]
: [
xs .slice (0, xs .length / rows),
... rotate(makeSpiral (xs .slice (xs .length / rows), xs.length / rows))
]
const range = (lo, hi) =>
[...Array (hi - lo + 1)] .map ((_, i) => lo + i)
const generateMatrix = (n) =>
makeSpiral (range (1, n * n), n)
console .log (generateMatrix (4))
A sharp eye will note that rotate is different here from the older question. transpose (reverse (m)) returns a clockwise rotated version of the input matrix. reverse (transpose (m)) returns a counter-clockwise rotated one. Similarly, here we rotate the result of the recursive call before including it; whereas in the other question we recurse on the rotated version of the matrix. Since we're reversing that process, it should be reasonably clear why.
The main function is makeSpiral, which takes an array and the number of rows to spiral it into and returns the spiraled matrix. (If rows is not a factor of the length of the array, the behavior might be crazy.) generateMatrix is just a thin wrapper around that to handle your square case by generating the initial array (using range) and passing it to makeSpiral.
Note how makeSpiral works with rectangles other than squares:
makeSpiral ([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], 2) //=>
// [
// [ 1, 2, 3, 4, 5, 6],
// [12, 11, 10, 9, 8, 7]
// ]
makeSpiral ([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], 3) //=>
// [
// [ 1, 2, 3, 4],
// [10, 11, 12, 5],
// [ 9, 8, 7, 6]
// ]
makeSpiral ([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], 4) //=>
// [
// [ 1, 2, 3],
// [10, 11, 4],
// [ 9, 12, 5],
// [ 8, 7, 6]
// ]
makeSpiral ([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], 6) //=>
// [
// [ 1, 2],
// [12, 3],
// [11, 4],
// [10, 5],
// [ 9, 6],
// [ 8, 7]
// ]
The other functions -- range, reverse, transpose, and rotate -- are general purpose utility functions for working with arrays or matrices.
Here's one solution.
I keep the current "moving direction" in dx and dy, such that the next matrix element indices are given by x+dx and y+dy.
If the next item is already filled or is out of bounds, I change this direction clockwise. Otherwise, I fill it with the next value.
const size = 6;
const matrix = Array(size).fill().map(() => Array(size).fill(0));
let x = -1;
let y = 0;
let dx = 1;
let dy = 0;
function changeDirection() {
if (dx === 1) {
dx = 0;
dy = 1;
} else if (dy === 1) {
dy = 0;
dx = -1;
} else if (dx === -1) {
dx = 0;
dy = -1;
} else {
dx = 1;
dy = 0;
}
}
for (let i = 0; i < size * size; i++) {
const yNext = y + dy;
const xNext = x + dx;
const nextRow = matrix[yNext] || [];
const nextItemContent = nextRow[xNext];
if (nextItemContent === undefined || nextItemContent > 0) {
changeDirection();
i--;
continue;
}
y = yNext;
x = xNext;
matrix[y][x] = i + 1;
}
const result = document.getElementById('result');
matrix.forEach(row => {
row.forEach(value => {
result.innerHTML += value.toString().padStart(3);
});
result.innerHTML += '\n';
});
<pre id="result"></pre>
I'm calculating the index, each number should go in a linear array
console.clear();
Array.prototype.range = function(a, b, step) {
step = !step ? 1 : step;
b = b / step;
for(var i = a; i <= b; i++) {
this.push(i*step);
}
return this;
};
const spiral = function(dimen) {
"use strict";
const dim = dimen;
const dimw = dim;
const dimh = dim;
var steps = [1, dimh, -1, -dimh];
var stepIndex = 0;
var count = 1;
var countMax = dimw
var dec = 0
var index = 0;
var arr = [];
arr = arr.range(1, dimh * dimw)
const newArr = arr.reduce((coll, x, idx) => {
index += steps[stepIndex]
coll[index-1] = idx+1;
if (count === countMax) {count = 0; stepIndex++; dec++;}
if (dec === 1) {dec = -1; countMax--}
if (stepIndex == steps.length) {stepIndex = 0}
count++;
return coll;
}, []);
var ret = []
while (newArr.length) {
ret.push(newArr.splice(0,dimw))
}
return ret
}
console.log(spiral(3))
console.log(spiral(4))
console.log(spiral(5))
var n=14; // size of spiral
var s=[]; // empty instruction string
function emp() {} // no move
function xpp() {xp++;} // go right
function xpm() {xp--;} // go left
function ypp() {yp++;} // go down
function ypm() {yp--;} // go up
var r=[xpp,ypp,xpm,ypm]; // instruction set
s.push(emp); // push 'no move' (used for starting point)
var c=n-1;
while (c-->0) s.push(r[0]); // push first line - uses a different rule
for (var i=1;i<2*n-1;i++) { // push each leg
c=Math.floor((2*n-i)/2);
while (c-->0) s.push(r[i%4]);
}
var sp=new Array(n); // spiral array
for (var i=0;i<n;i++) sp[i]=new Array(n);
var xp=0; // starting position
var yp=0;
for (var i=0;i<n*n;i++) {
s[i](); // execute next instruction
sp[yp][xp]=i+1; // update array
}
for (var i=0;i<n;i++) console.log(sp[i].toString()); // log to console
This code makes a macro of functions to generate a run sequence, for example:
'right4, down4, left4, up3, right3, down2, left2, up1, right1
and then implements it.
Here is a solution to Spiral Matrix from leetcode, maybe this can help
https://leetcode.com/problems/spiral-matrix/
var spiralOrder = function(matrix) {
if (matrix.length == 0) {
return [];
}
let result = [];
let rowStart = 0;
let rowEnd = matrix.length - 1;
let colStart = 0;
let colEnd = matrix[0].length - 1;
while (true) {
// top
for (let i = colStart; i <= colEnd; i++) {
result.push(matrix[rowStart][i]);
}
rowStart++;
if (rowStart > rowEnd) {
return result;
}
// right
for (let i = rowStart; i <= rowEnd; i++) {
result.push(matrix[i][colEnd]);
}
colEnd--;
if (colEnd < colStart) {
return result;
}
// bottom
for (let i = colEnd; i >= colStart; i--) {
result.push(matrix[rowEnd][i]);
}
rowEnd--;
if (rowEnd < rowStart) {
return result;
}
// left
for (let i = rowEnd; i >= rowStart; i--) {
result.push(matrix[i][colStart]);
}
colStart++;
if (colStart > colEnd) {
return result;
}
}
return result;
};
console.log(
spiralOrder([[2, 3, 4], [5, 6, 7], [8, 9, 10], [11, 12, 13], [14, 15, 16]])
);
console.log(spiralOrder([[7], [9], [6]]));
console.log(spiralOrder([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]));
console.log(spiralOrder([[1, 2, 3], [4, 5, 6], [7, 8, 9]]));
Here's my answer using only one for loop -
function matrix(n) {
const arr = [];
let row = 0;
let column = 0;
let counter = 1;
let edge = n - 1;
let leftToRightRow = false;
let topToBottomCol = false;
let rightToLeftRow = false;
let bottomToTopCol = false;
for (i = 0; i < n * n; i++) {
if (column <= edge && !leftToRightRow) {
if (!Array.isArray(arr[row])) {
arr[row] = []; // if array is not present at this index, then insert one
}
arr[row][column] = counter;
if (column == edge) {
row = row + 1;
leftToRightRow = true;
} else {
column = column + 1;
}
counter = counter + 1;
} else if (column === edge && !topToBottomCol) {
if (!Array.isArray(arr[row])) {
arr[row] = []; // if array is not present at this index, then insert one
}
arr[row][column] = counter;
if (row === edge) {
column = column - 1;
topToBottomCol = true;
} else {
row = row + 1;
}
counter = counter + 1;
} else if (column >= 0 && !rightToLeftRow) {
arr[row][column] = counter;
if (column === 0) {
row = row - 1;
rightToLeftRow = true;
} else {
column = column - 1;
}
counter = counter + 1;
} else if (row >= n - edge && !bottomToTopCol) {
arr[row][column] = counter;
if (row === n - edge) {
column = column + 1;
bottomToTopCol = true;
//setting these to false for next set of iteration
leftToRightRow = false;
topToBottomCol = false;
rightToLeftRow = false;
edge = edge - 1;
} else {
row = row - 1;
}
counter = counter + 1;
}
}
return arr;
}
Solution is implemented in C++, but only logic matter then you can do it in any language:
vector<vector<int> > Solution::generateMatrix(int A) {
vector<vector<int>> result(A,vector<int>(A));
int xBeg=0,xEnd=A-1;
int yBeg=0,yEnd=A-1;
int cur=1;
while(true){
for(int i=yBeg;i<=yEnd;i++)
result[xBeg][i]=cur++;
if(++xBeg>xEnd) break;
for(int i=xBeg;i<=xEnd;i++)
result[i][yEnd]=cur++;
if(--yEnd<yBeg) break;
for(int i=yEnd;i>=yBeg;i--)
result[xEnd][i]=cur++;
if(--xEnd<xBeg) break;
for(int i=xEnd;i>=xBeg;i--)
result[i][yBeg]=cur++;
if(++yBeg>yEnd) break;
}
return result;
}
Solition in c#:
For solving this problem we use loops for each moving directions
public IList<int> SpiralOrder(int[][] matrix) {
var result = new List<int>();
var n = matrix[0].Length;
var m = matrix.Length;
var i = 0;
var j = 0;
var x = 0;
var y = 0;
while (true)
{
//left to right moving:
while (x <= n - 1 - i)
{
result.Add(matrix[y][x]);
x++;
}
if (result.Count == n * m)
return result;
x--;y++;
//up to down moving:
while (y <= m - 1 - j)
{
result.Add(matrix[y][x]);
y++;
}
if (result.Count == n * m)
return result;
y--;x--;
//right to left moving:
while (x >= j)
{
result.Add(matrix[y][x]);
x--;
}
if (result.Count == n * m)
return result;
x++;y--;
//down to up moving:
while (y > j)
{
result.Add(matrix[y][x]);
y--;
}
if (result.Count == n * m)
return result;
y++;x++;
i++;
j++;
}
}

loop over array, but not every element

I would like to iterate over the array and getting an average from 5 next elements, not from the whole array. I try to do it by code bellow, but it doesn´t work. I appreciate any kind of help or suggestions.
function standardDeviation(array) {
let newArray = [];
for (let i = 0; i < array.length; i++) {
let tempArray = [];
const arrAvg = tempArray =>
tempArray.reduce((a, b) => a + b, 0) / tempArray.length;
newArray += tempArray;
for (let j = array[i]; (j = array[i + 5]); i++) {
tempArray += array[j];
}
}
console.log(newArray);
return newArray;
}
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
standardDeviation(arr);
You could slice a given array and take only five elements for getting an average.
function standardDeviation(array) {
const arrAvg = tempArray => tempArray.reduce((a, b) => a + b, 0) / tempArray.length;
return array.map((_, i, a) => arrAvg(a.slice(i, i + 5)));
}
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(standardDeviation(arr));
You could try using the slice() function of array element.
// simulated loop index
var curr_index_pos = 3;
// entire array
var array_full = [1,2,3,4,5,6,7,8,9,10];
// array with 5 next values from "curr_index_pos"
var array_5 = array_full.slice(curr_index_pos,curr_index_pos+5);
var sum = 0;
for( var i = 0; i < array_5.length; i++ ) {
sum += parseInt( array_5[i] );
}
var avg = sum/array_5.length;
console.log("array_5", array_5);
// [4,5,6,7,8]
console.log("sum", sum);
// 30
console.log("avg", avg);
// 6

How to find non repeated numbers in an Array using JavaScript?

Dear all I'm trying to find non repeated value in an array using javascript.I have written some code but it not working properly ..can you guys tell me where is the problem.thanks.
var arr = [-1, 2, 5, 6, 2, 9, -1, 6, 5, -1, 3];
var n = arr.length;
var result = '';
function nonrep() {
for (var i = 0; i < n; i++) {
var j;
for (j = 0; j < n; j++)
if (i != j && arr[i] == arr[j]) {
result = arr[i];
break;
}
if (j == n)
return arr[i];
}
return result;
}
console.log(nonrep())
There is possibly a more neat approach to this solution, but this works as expected by filtering the array and compare it's current value with the array items itself (expect current item's index value).
const sampleArray = [1,2,3,7,2,1,3];
const getNonDuplicatedValues = (arr) =>
arr.filter((item,index) => {
arr.splice(index,1)
const unique = !arr.includes(item)
arr.splice(index,0,item)
return unique
})
console.log("Non duplicated values: " , ...getNonDuplicatedValues(sampleArray))
Some changes:
Move all variable declarations inside of the function.
Use a function parameter for the handed over array, keep the function pure.
Declare all needed variables at top of the function in advance.
Take an array as result array unique.
Check i and j and if equal continue the (inner) loop.
Check the value at i and j and exit the (inner) loop, because a duplicate is found.
Take the check at the end of the inner loop and check the index j with the length of the array l, and if equal push the value to unique.
Use a single return statement with unique array at the end of the outer loop.
function getUnique(array) {
var l = array.length,
i, j,
unique = [];
for (i = 0; i < l; i++) {
for (j = 0; j < l; j++) {
if (i === j) {
continue;
}
if (array[i] === array[j]) {
break;
}
}
if (j === l) {
unique.push(array[i]);
}
}
return unique;
}
console.log(getUnique([-1, 2, 5, 6, 2, 9, -1, 6, 5, -1, 3]));
Another solution could be to check if indexOf and lastIndexOf returns the same value. Then you found a unique value.
var array = [-1, 2, 5, 6, 2, 9, -1, 6, 5, -1, 3],
unique = array.filter((v, i) => array.indexOf(v) === array.lastIndexOf(v));
console.log(unique);
You could first use reduce to get one object with count for each number element and then filter on Object.keys to return array of non-repeating numbers.
var arr=[-1,2,5,6,2,9,-1,6,5,-1,3];
var obj = arr.reduce((r, e) => (r[e] = (r[e] || 0) + 1, r), {});
var uniq = Object.keys(obj).filter(e => obj[e] == 1).map(Number)
console.log(uniq)
Solution with for loop.
var arr = [-1, 2, 5, 6, 2, 9, -1, 6, 5, -1, 3];
var uniq = [];
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < arr.length; j++) {
if (arr[i] == arr[j] && i != j) break;
else if (j == arr.length - 1) uniq.push(arr[i])
}
}
console.log(uniq)
Another simple approach
var arr = [1,1,2,3,3,4,4,5];
let duplicateArr = [];
var repeatorCheck = (item) => {
const currentItemCount = arr.filter(val => val=== item).length;
if(currentItemCount > 1) duplicateArr.push(item);
return currentItemCount;
}
var result = arr.filter((item,index) => {
var itemRepeaterCheck = !duplicateArr.includes(item) && repeatorCheck(item);
if(itemRepeaterCheck === 1){
return item;
}
});
console.log(result);
let arr = [1, 2, 1, 3, 3, 5];
function nonRepeatableNo(arr) {
let val = []
for (let i = 0; i < arr.length; i++) {
let count = 0;
for (let j = 0; j < arr.length; j++) {
if (arr[i] === arr[j]) {
count += 1
}
}
if (count === 1) {
val.push(arr[i])
}
}
console.log(val)
}
nonRepeatableNo(arr)
const arr = [-1, 2, 5, 6, 2, 9, -1, 6, 5, -1, 3];
const non_repeating = arr.filter(num => arr.indexOf(num) === arr.lastIndexOf(num))
console.log(non_repeating)
Filtering only unique elements according to OP request:
This uses for loops, as requested. It returns an array containing only elements appearing once in the original array.
var arr = [-1, 2, 5, 6, 2, 9, -1, 6, 5, -1, 3];
var n = arr.length;
var result = [];
function nonrep() {
for (var i = 0; i < n; i++) {
for (var j=0 ; j < n; j++)
if (i!=j && arr[i]==arr[j])
break;
if(j==n)
result.push(arr[i]);
}
return result;
}
console.log(nonrep())
var arr1 = [45, 4,16,25,45,4,16, 9,7, 16, 25];
var arr=arr1.sort();
console.log(arr);
var str=[];
arr.filter(function(value){
if( arr.indexOf(value) === arr.lastIndexOf(value))
{ str.push(value);
console.log("ntttttttttttttnnn" +str)
}// how this works ===============A
})
O/P
7,9
Please try the below code snippet.
var arr = [-1, 2, 5, 6, 2, 9, -1, 6, 5, -1, 3];
var uniqArr = [];
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < arr.length; j++) {
if (arr[i] == arr[j] && i != j) break;
else if (j == arr.length - 1){
uniqArr.push(arr[i])
}
}
}
console.log(uniqArr)
this ES6 code worked for me :
a.map(c=>a.filter(b=>c==b)).filter(e=>e.length<2).reduce((total, cur)=> total.concat(cur), [])
Here is a working method with loops.
var arr = [-1,2,5,6,2,9,-1,6,5,-1,3];
var len = arr.length;
const result = arr
.filter(value=>{
var count=0;
for(var i=0;i<len;i++)
{
if(arr[i]===value)
count++;
}
return count===1;
})
console.log(result);
const sampleArr = [-1, 2, 5, 6, 2, 9, -1, 6, 5, -1, 3];
function getUnique(arr){
const result=[]
const obj={}
for(let i=0;i<arr.length;i++){
if(!obj[arr[i]]){
obj[arr[i]]=true
result.push(arr[i])
}else{
const index= result.indexOf(arr[i])
if(index!==-1){
result.splice(result.indexOf(arr[i]),1)
}
}
}
return result
}
const uniqueArr= getUnique(sampleArr)
console.log(uniqueArr)
Here is the solution..
var x = [1,1,2,3,2,4]
var res = []
x.map(d => {
if(res.includes(d)) {
// remove value from array
res = res.filter((a) => a!=d)
} else {
// add value to array
res.push(d)
}
})
console.log(res) // [3,4]
//without using any filter also with minimum complexity
const array = [1 , 2, 3, 4, 2, 3, 1, 6, 8,1,1 ];
const unique = new Set();
const repetedTreses = new Set();
for(let i=0; i<array.length; i++) {
if(!unique.has(array[i]) && !repetedTreses.has(array[i])){
unique.add(array[i]);
}else{
repetedTreses.add(array[i]);
unique.delete(array[i]);
}
}
let uniqueElements=[...unique];
console.log(uniqueElements);
You can use filter and indexOf for that:
console.log(
[-1, 2, 5, 6, 2, 9, -1, 6, 5, -1, 3].filter((v, i, a) => a.indexOf(v, i + 1) === -1 )
);

Javascript: Bubble Sort

I have made a bubble sort algorithm (sorta) using JS. It works sometimes, but the problem is that it only iterates through the array once. Here is my code:
function bubble(arr) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] > arr[i + 1]) {
var a = arr[i]
var b = arr[i + 1]
arr[i] = b
arr[i + 1] = a
}
}
return arr;
}
Another bubble sort implementation:
const bubbleSort = array => {
const arr = Array.from(array); // avoid side effects
for (let i = 1; i < arr.length; i++) {
for (let j = 0; j < arr.length - i; j++) {
if (arr[j] > arr[j + 1]) {
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
}
}
}
return arr;
};
You need an inner loop to complete the sort correctly:
function bubble(arr) {
var len = arr.length;
for (var i = 0; i < len ; i++) {
for(var j = 0 ; j < len - i - 1; j++){ // this was missing
if (arr[j] > arr[j + 1]) {
// swap
var temp = arr[j];
arr[j] = arr[j+1];
arr[j + 1] = temp;
}
}
}
return arr;
}
document.write(bubble([1,9,2,3,7,6,4,5,5]));
Please look at the following sequence:
[5, 4, 3, 2, 1]
Now lets say you need to sort this in the ascending order using bubble sort.
So, you iterate the array and swap adjacent elements which are ordered otherwise.
Here is what you will get after the completion of the iteration
[4, 3, 2, 1, 5]
Now if you do this another time, you will get this:
[3, 2, 1, 4, 5]
Likewise, you need to repeat the iteration enough times to get it sorted fully. This means you need 2 nested loops. The inner loop is to iterate the array and the outer loop is to repeat the iteration.
Please see the step-by-step example of this article.
const bubbleSort = (array)=>{
let sorted = false;
let counter =0;
while(!sorted){
sorted = true;
for(let i =0; i < array.length -1 -counter; i++){
if(array[i] > array[i+1]){
helper(i,i+1,array);
sorted = false;
}
}
counter++;
}
return array;
}
//swap function
function helper(i,j, array){
return [array[i],array[j]] = [array[j],array[i]]
}
let array=[8,5,2,9,5,6,3];
console.log(bubbleSort(array))
var array = [6,2,3,7,5,4,1];
function bubbleSort(arr) {
for(let j=0;j<arr.length;j++) {
for(let i = 0; i < arr.length; i++) {
if(arr[i]>arr[i+1] && (i+1 < arr.length)) {
var temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
}
}
}
return arr;
}
console.log(bubbleSort(array));
My bubble sort with just a while loop :
function bubbleSort(arr){
var sorted = false
while (!sorted){
sorted = true;
arr.forEach(function (element, index, array){
if (element > array[index+1]) {
array[index] = array[index+1];
array[index+1] = element;
sorted = false;
}
});
}
}
function bubble(arr) {//You need Two Loops for Bubble sort
for (var i = 0; i < arr.length; i++) {//Outer Loop
for(var j=0; j < arr.length - 1; j++){//Inner Loop
if (arr[j] > arr[j + 1]) {
var a = arr[j]
var b = arr[j + 1]
arr[j] = b
arr[j + 1] = a
}
}
}
return arr;
}
Another form of bubble sort includes starting at the end of the array and placing the smallest element first and going till the largest. This is the code:
function bubbleSort(items) {
var length = items.length;
for (var i = (length - 1); i >= 0; i--) {
//Number of passes
for (var j = (length - i); j > 0; j--) {
//Compare the adjacent positions
if (items[j] < items[j - 1]) {
//Swap the numbers
var tmp = items[j];
items[j] = items[j - 1];
items[j - 1] = tmp;
}
}
}
}
Note Bubble sort is one of the slowest sorting algorithms.
It works for me. I commented the code for more understanding
bubbleSort = (numbersArray) => {
const arrayLenght = numbersArray.length;
for (let i = 0; i < arrayLenght; i++) {
for(let j = 0; j < arrayLenght; j++) {
// Print only to debug
// console.log(`i: ${i} - j: ${j}`);
// console.log(`numbersArray[i]: ${numbersArray[i]} | numbersArray[j]: ${numbersArray[j]}`);
// Check if current number is greater than the next number
if (numbersArray[j] > numbersArray[j + 1]) {
// Store current value to generate swap
const currentNumber = numbersArray[j];
// Now the current position get value of the next position
// And de next position get value of the current position
numbersArray[j] = numbersArray[j + 1];
numbersArray[j + 1] = currentNumber;
}
}
}
// Debug: Print the sorted array
console.log(`sorted array: ${numbersArray.toString()}`);
}
const numbers = [
[3, 10, 5, 7],
[8, 5, 2, 9, 5, 6, 3],
[4, 50, 28, 47, 9, 2097, 30, 41, 11, 3, 68],
[3, 10, 5, 7, 8, 5, 2, 9, 5, 6, 3]
];
numbers.forEach(element => {
bubbleSort(element);
});
Output:
sorted array: 3,5,7,10
sorted array: 2,3,5,5,6,8,9
sorted array: 3,4,9,11,28,30,41,47,50,68,2097
sorted array: 2,3,3,5,5,5,6,7,8,9,10
var arr = [5, 3, 4, 1, 2, 6];
function sort (arr) {
for(let i=0; i < arr.length - 1; i++) {
if(arr[i] > arr[i+1]) {
let b = arr[i+1];
arr[i+1] = arr[i];
arr[i] = b;
i = -1; // Resets the loop
}
}
return arr;
}
console.log(sort(arr));
Try this (performance upgrade):
function bubbleSort(inputArr, reverse = false) {
const len = inputArr.length;
for (let i = 0; i < len; i++) {
for (let j = i + 1; j < len; j++) {
let a = inputArr[i];
let b = inputArr[j];
if (reverse ? a < b : a > b) {
const tmp = inputArr[j];
inputArr[j] = inputArr[i];
inputArr[i] = tmp;
}
}
}
return inputArr;
}
Use:
arr = [234,2,4,100, 1,12,5,23,12];
console.log(bubbleSort(arr)); // or console.log(bubbleSort(arr, true));
You need another loop:
var arr = [2, 1]
for(let i = 0;i<arr.length;i++){
for(let b = 0; b<arr.length;i++){
if(arr[b] > arr[b+1]){
var first = arr[b]
var second = arr[b + 1]
arr[b] = second
arr[b + 1] = first
}
}
}
Hope this helps I would recommend using quick sort if you want a high efficiency though.
const bubbleSort = (inputArr) => {
const len = inputArr.length;
for (let i = 0; i < len; i++) {
for (let j = 0; j < len; j++) {
if (inputArr[j] > inputArr[j + 1]) {
let tmp = inputArr[j];
inputArr[j] = inputArr[j + 1];
inputArr[j + 1] = tmp;
}
}
}
return inputArr;
};
const numbers = [50, 30, 10, 40, 60];
console.log(bubbleSort(numbers));
// Output: [ 10, 30, 40, 50, 60 ]
function bubbleSort(array) {
var done = false;
while (!done) {
//alert(1)
done = true;
for (var i = 1; i < array.length; i += 1) {
if (array[i - 1] > array[i]) {
//alert(2)
done = false;
var tmp = array[i - 1];
array[i - 1] = array[i];
array[i] = tmp;
}
}
}
return array;
}
Another way would be like this:
function bubbleSort(arr) {
let swapped;
do {
swapped = false;
for (var i = 0; i < arr.length; i++) {
if (arr[i] > arr[i + 1]) {
swapped = true;
var tmp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = tmp;
}
}
} while (swapped);
return arr;
}
let myArray = [8, 1, 2, 5, 51, 13, 15, 33, 123, 100, 22];
console.log(bubbleSort(myArray));
Explanation:
In this function we are going to declare a swapped variable that is being set to false inside the DO WHILE loop, this is being done as a fail-safe not to end up with an infinite loop.
Inside the loop, we have another FOR loop which iterates through the given array and checks if the current value is greater than the next (which we don't want, we need ascending order).
When the IF the condition is true, we are going to swap the variables and assign true for the swapped variable, this is done because we want to keep on the DO WHILE loop untill everything is sorted.
package hasan;
public class hssd {
public static void main(String[] args) {
int t=9;
int g=20;
for (t=g;t>19;++t){
System.out.println(7);
int f=12;
int r=15;
for(r=f;r>5;++r)
System.out.println(r+1000000000+"*"+1000000000);
}
}
}

Categories