Array.push inside 2nd nested For Loop - javascript

Why Array.push doesnt work inside Nested For Loop? But it works if I replace 2nd for Loop with forEach
var longestCommonPrefix = function (strs) {
if (strs.length === 1) {
return strs.join('')
}
let reference = strs[0].split('');
let answer = [];
let final = [];
for (let i = 1; i < strs.length; i++) {
let check = strs[i].split('')
for (let x = 0; x < reference.length; x++) {
if (reference[x] === check[x]) {
answer.push(check[x]) //WHY THIS WONT WORK?
} else return
}
reference = answer
}
console.log(answer)
};
longestCommonPrefix(["flower", "flow", "flight"]);

return is used to exit the function, use break to only exit the loop
var longestCommonPrefix = function(strs) {
if (strs.length === 1) {
return strs.join('')
}
let reference = strs[0].split('');
let answer = [];
let final = [];
for (let i = 1; i < strs.length; i++) {
let check = strs[i].split('')
for(let x = 0 ; x<reference.length ; x++){
if(reference[x] === check[x]){
answer.push(check[x]) //WHY THIS WONT WORK?
}else break
}
reference = answer
}
console.log(answer)
};
longestCommonPrefix(["flower", "flow", "flight"])

Related

Search String Custom function algorithm

I want to condition the string that I Inputted value ("ello") and variable("hello").
If It found in string("hello"), the return value should be "ello".
If not found, the return value should be -1.
But it returned "llll" 4 times because of condition (strs[i] == arrayS[tempVal]).
How can I get the correct answer as mentioned above?
var stres = "hello";
var strs = [...stres];
function searchStr(s) {
let arrayS = [...s];
let tempVal = 0;
let tempStr = [];
while (tempVal < arrayS.length) {
for (let i = 0; i < strs.length; i++) {
if (strs[i] == arrayS[tempVal]) {
tempStr.push(arrayS[tempVal]);
}
}
tempVal++;
}
return tempStr;
}
const res = searchStr("ello");
console.log('res', res)
According to you, logic is correct just break the for a loop when the condition is fulfilled. Check below snippet and console output.
var stres = "hello";
var strs = [...stres];
function searchStr(s) {
let arrayS = [...s];
let tempVal = 0;
let tempStr = [];
while (tempVal < arrayS.length) {
for (let i = 0; i < strs.length; i++) {
if (strs[i] == arrayS[tempVal]) {
tempStr.push(arrayS[tempVal]);
break;
}
}
tempVal++;
}
return tempStr;
}
const res = searchStr("ello");
const resS = res.join('');
console.log('res = ', res);
console.log('resS = ', resS);

How to avoid multiple for loops

I am new in JavaScript data structure. I am working on linked list in JavaScript. I want to create a function which can find the distance between nodes. I have created a function which work perfectly what i want. But i think this is not the way of writing time efficient code. Is there any way to replace those for loops in distance function to any other code that can give the same result with the time efficiency. Here is the distance function code.
linkList.prototype.distance = function (val1, val2) {
let node1 = this.search(val1);
let node2 = this.search(val2);
let info = {};
let node1Values = [...Object.keys(node1)];
let node2Values = [...Object.keys(node2)];
for (let i = 0; i < node1Values.length; i++){
for (let j = 0; j < node2Values.length; j++){
info[`Distance From ${node1Values[i]} To ${node2Values[j]} is:`] =
Math.abs(node1[node1Values[i]].Index - node2[node2Values[j]].Index);
}
}
return info;
};
Here is the search function code which is used by distance function.
linkList.prototype.search = function (value) {
let info = {};
let curNode = this.head;
let c = 0;
let duplicate = 1;
while (curNode) {
if (curNode.value === value) {
let info_arr = {};
let val = curNode.value;
let next = null;
if (curNode.next) {
next = curNode.next.value;
}
let prev = null;
if (curNode.prev) {
prev = curNode.prev.value;
}
let index = c;
info_arr["Value"] = val;
info_arr["Index"] = index;
info_arr["Next"] = next;
info_arr["Prev"] = prev;
if (info[curNode.value]) {
info[curNode.value + ":" + duplicate] = info_arr;
duplicate++;
} else {
info[curNode.value] = info_arr;
}
}
curNode = curNode.next;
c++;
}
return info;
};
Here is the output of distance function when i console log it.

how to get distinct value from an array javascript

how can i get elements uniquely from an array if aa is twice time it should not count in a result if it is if a is three times it should count 1
var string = "aaabbccddde" // Expected result ade
var toArray = string.split("")
console.log(toArray)
var newArr = []
for(let i =0; i<toArray.length; i++) {
if(newArr.indexOf(toArray[i]) === -1) {
newArr.push(toArray[i])
}
}
console.log(newArr)
can't find the solution yet please guide thank
Maybe this function can help you:
function getUniques(str) {
const uniques = [];
const strs = str.split("");
for (let i = 0; i < strs.length; i++) {
const elm = strs[i];
for (let j = i; j < strs.length; j++) {
if(elm === uniques[uniques.length - 1]) break;
if (elm !== strs[j + 1]) {
uniques.push(elm);
break;
}
}
}
return uniques.join("");
}
Sample:
getUniques("aaaadaaabbbcccdeeeee22222222222232") // adabcde232

How to make for loop log line by line with 1sec delay in JS

My code will log all 10 lines in the order that I want (descending triangle), but I need it to delay 1 second before logging each successive line. I tried putting a setTimeout before the for loop, but that just caused a 1 second delay before printing all 10 lines concurrently.
function minusTen(num) {
var arr = '';
for (var i = num; i > 0; i--) {
arr += '*';
}
var newArr = arr.split('');
for (var j = num; j > 0; j--) {
newArr.pop();
console.log(newArr.join(' '));
}
}
minusTen(10);
I can use jQuery but I'd like to avoid having to implement Bootstrap if possible.
Thank you!
you can use setTimeout for it but then you will have to keep setTimeout inside the for loop. you can also use setInterval here and clear the interval if num becomes 0. something like this:
function minusTen(num) {
var arr = '';
for (var i = num; i > 0; i--) {
arr += '*';
}
var newArr = arr.split('');
var interval = setInterval(function(){
newArr.pop();
console.log(newArr.join(' '));
num--;
if(!num)
clearInterval(interval);
}, 1000)
}
minusTen(10);
You can use a function. Check the .length of newArr, if greater than 0, call function again
function minusTen(num) {
var arr = '';
for (var i = num; i > 0; i--) {
arr += '*';
}
var newArr = arr.split('');
function fn() {
if (newArr.length)
setTimeout(function() {
console.log(newArr.join(" "));
newArr.pop();
fn()
}, 1000)
else
console.log("done, newArr.length:", newArr.length);
}
fn()
}
minusTen(10);
function minusTen(num) {
var arr = '';
for (var i = num; i > 0; i--) {
arr += '*';
}
var newArr = arr.split('');
function printLine(counter){
var k = counter;
window.setTimeout(function(){
console.log(newArr.join(' '));
newArr.pop();
}, k*1000);
console.log(k);
}
for (var j = num; j > 0; j--) {
printLine(j);
}
}
minusTen(10);
It's straightforward with async/await. delay holds the execution of the code for a specified amount of time.
async function minusTen(num) {
var arr = '';
for (var i = num; i > 0; i--) {
arr += '*';
}
var newArr = arr.split('');
for (var j = num; j > 0; j--) {
newArr.pop();
await delay(1000)
console.log(newArr.join(' '));
}
}
function delay(time) {
return new Promise((resolve) => setTimeout(resolve, time))
}
minusTen(10);
You can use setTimeout with an offset. Just add whatever parameters you need to the log function.
function log(offSet) {
setTimeout(() => {
const str = new Array(offSet + 1).join('*');
console.log(str);
}, 1000 * offSet);
}
for(let i = 1; i < 11; i ++) {
log(i);
}
https://jsfiddle.net/ycreaL9w/
If you wanted to reduce your code footprint a little you could do something like this:
const printStars = (n) => {
// Make sure we don't try to print zero stars
if (n > 0) {
// Fill an array with n stars
const arr = Array(n).fill('*').join(' ');
console.log(arr);
// After a second, reduce n by 1 and call
// the function again
setTimeout(() => printStars(--n), 1000);
}
}
printStars(10);
DEMO
It's worth pointing out here, however, that IE/Opera don't support Array.fill.
If you need to support them use an for/loop like in your example. Here I've separated out that code into its own function.
const getStars = (n) => {
let arr = [];
for (let i = 0; i < n; i++) {
arr.push('*');
}
return arr.join(' ');
}
const printStars = (n) => {
if (n > 0) {
console.log(getStars(n));
setTimeout(() => printStars(--n), 1000);
}
}
DEMO 2

removing multiple arrays from a 2D array

My web app is taking in arbitrarily large 2D arrays that sometimes look something like this:
var multiArray = [["","","",""],[1,2,3],["hello","dog","cat"],["","","",""]];
I want to write a function to take out every array inside of multiArray that is comprised entirely of quotes. In other words, any array that looks like this:
["","","",""]
should be deleted from multiArray.
I tried writing the following function, but the problem with using splice in a for loop is that splicing will change the length of the array, and I end up trying to access undefined elements. Please help!
Thanks!
Here's the incorrect function I wrote:
function cleanWhitespace(arrayOfArrays) {
var i;
var arrayOfArraysLength = arrayOfArrays.length;
for (i = 0; i < arrayOfArraysLength; i++) {
var cleanedArray = $.grep(arrayOfArrays[i], function(element) {
return element != ""
});
if (cleanedArray.length == 0) {
arrayOfArrays.splice(i, 1);
}
}
return arrayOfArrays;
};
You can use $.grep :
multiArray = $.grep(multiArray, function(v){
return v.join('');
});
Fiddle : http://jsfiddle.net/scZcB/
on the fly:
var multiArray = [["","","",""],[1,2,3],["hello","dog","cat"],["","","",""]];
var outputArr = removeQuoteArrays(multiArray);
console.log(outputArr);
function removeQuoteArrays(arr) {
var outputArr = [];
for (var i = 0; i < arr.length; i++) {
var currArr = arr[i];
var isAllQuotes = true;
for (var j = 0; j < currArr.length; j++) {
if (currArr[j] != "") {
isAllQuotes = false;
break;
}
}
if (!isAllQuotes) {
outputArr.push(currArr);
}
}
return outputArr;
}
Here's a JSFiddle.
Create a new array instead.
// Only add if...
cleanedArray = multiArray.filter(function(arr){
// Some elements are not blank
return arr.some(function(e){ return e !== "" })
})
I added a length check to your function to break out of the loop if the index reaches the array length:
if (i >= arrayOfArrays.length)
break;
Which makes:
function cleanWhitespace(arrayOfArrays) {
var i;
var arrayOfArraysLength = arrayOfArrays.length;
for (i = 0; i < arrayOfArraysLength; i++) {
var cleanedArray = $.grep(arrayOfArrays[i], function(element) {
return element != ""
});
if (cleanedArray.length == 0) {
arrayOfArrays.splice(i, 1);
if (i >= arrayOfArrays.length)
break;
}
}
return arrayOfArrays;
};
var multiArray = [["","","",""],[1,2,3],["hello","dog","cat"],["","","",""]];
function cleanWhitespace(arrayOfArrays) {
for (var i = 0; i < arrayOfArrays.length; i++) {
var emptyElements = 0;
for (var j = 0; j < arrayOfArrays[i].length; j++ ) {
if (arrayOfArrays[i][j] === "") {
emptyElements++;
}
}
if (emptyElements === arrayOfArrays[i].length) {
arrayOfArrays.splice(i, 1);
}
}
return arrayOfArrays;
}
console.log(cleanWhitespace(multiArray));
http://jsfiddle.net/4Jfr9/

Categories