I'm new in JavaScript and i am trying to print only two elements from array with FOR LOOP and brake & continue statements
for example i want to be printed 3 and 8
I tried this:
var array= [1,2,3,4,5,6,7,8];
for (var i = 0; i < array.length; i++) {
if (i == 3) {
alert(i);
continue;
}
if ( i == 8) {
alert(i);
}
}
All arrays start at the first position of 0 and go up from there. So in your code you are thinking you are comparing 3 == 3 in but really you are comparing 2 == 3. If you compare the array position value instead of the loop value your problem is fixed.
var array = [1, 2, 3, 4, 5, 6, 7, 8];
for (var i = 0; i < array.length; i++) {
if (array[i] == 3) {
alert(array[i]);
}
else if (array[i] == 8) {
alert(array[i]);
}
}
Try this one if you need to check for values in array and not index. Imo, values in array need not be similar as index values,they can be anything.
var array= [1,2,3,4,5,6,7,8];
for(var i = 0; i < array.length; i++)
{
if (array[i]== 3 || array[i] == 8)
{
alert(array[i]);
}
}
What about using a filter?
const array = [1,2,3,4,5,6,7,8];
const matches = array.filter(a => a === 3 || a === 8);
console.log(matches[0], matches[1]);
// The filter uses the lambda function. It's the same thing as the following:
const matches = array.filter(function(a) {
return a === 3 || a === 8;
});
Related
I've tried merging the two arrays but the output i get is [ 0, 3, 3, 4, 4 ]
function mergeSortedArrays(arr1, arr2) {
var i = 0;
var j = 0;
var arr3 = [];
if (arr1 === undefined || arr1.length == 0) {
return arr2;
}
if (arr2 === undefined || arr2.length == 0) {
return arr1;
}
while (i < arr1.length - 1 && j < arr2.length - 1) {
if (arr1[i] < arr2[j]) {
arr3.push(arr1[i]);
i++;
} else {
arr3.push(arr2[j]);
j++;
}
}
return arr3;
}
console.log(mergeSortedArrays([0, 3, 4, 31], [3, 4, 6, 30]));
For this example, i know i haven't accounted for the case in which arrays are of different size but that is for a later problem. The code currently isn't even working for the basic case. It does not iterate all the way through and breaks midway. Can someone please address this problem. I've worked around with the while loop but the code still doesnt work.
You are making two mistakes.
In the while loop condition check of length of array not length - 1. This will not add last elements of both array.
Your while loop will end when one of the array will be completely loop because of &&. So after while add the remaining elements of other array.
function mergeSortedArrays(arr1, arr2) {
var i = 0;
var j = 0;
var arr3 = [];
if (arr1 === undefined || arr1.length == 0) {
return arr2;
}
if (arr2 === undefined || arr2.length == 0) {
return arr1;
}
while (i < arr1.length && j < arr2.length) {
if (arr1[i] < arr2[j]) {
arr3.push(arr1[i]);
i++;
} else {
arr3.push(arr2[j]);
j++;
}
}
if(i === arr1.length){
return arr3.concat(arr2.slice(j))
}
else if(j === arr2.length){
return arr3.concat(arr1.slice(i))
}
}
console.log(mergeSortedArrays([0, 3, 4, 31], [3, 4, 6, 30]));
First of all, the loop needs to iterate till arr1.lenght and arr2.lenght not till lenght - 1,
while (i < arr1.length && j < arr2.length )
Also, after the loop breaks, the reason being either one of the array loop variables has a false condition, before returning the array, you need to check if there are values left which are not yet inserted. This is important.
You can do this:
arr3.concat(arr1.slice(i)).concat(arr2.slice(j));
Hope it helps.
There are two things missing in your code:
The while loop is running for i < arr1.length - 1 for arr1 and j < arr2.length - 1 for arr2. That means it will run till 3rd index of arr1 and arr2. So the last index will not be executed in the loop. So you should refactor the loop as i < arr1.length for arr1 and j < arr2.length for arr2.
Next missing thing, you need to add the loop for remaining elements of remaining array. That means when you execute the code then all the elements of one loop will be pushed in the arr3 then one elements of another array will be missed and it will not be pushed in the arr3 (for same length of both array) and/or more than one elements of another array will be missed (for different length of both array). So you need to push the remaining elements of another array to the arr3.
I have added the refactored code of your code.
function mergeSortedArrays(arr1, arr2) {
var i = 0;
var j = 0;
var arr3 = [];
if (arr1 === undefined || arr1.length == 0) {
return arr2;
}
if (arr2 === undefined || arr2.length == 0) {
return arr1;
}
while (i < arr1.length && j < arr2.length) {
if (arr1[i] < arr2[j]) {
arr3.push(arr1[i]);
i++;
} else {
arr3.push(arr2[j]);
j++;
}
}
while (i < arr1.length) {
arr3.push(arr1[i]);
i++;
}
while (j < arr2.length) {
arr3.push(arr2[j]);
j++;
}
return arr3;
}
OR
you can use spread operator to merge both array and then you can use sort method of JS.
function mergeTwo(arr1, arr2) {
let result = [...arr1, ...arr2];
return result.sort((a,b) => a-b);
}
There is a simple one line solutions that does involve a resort. Using default parameters to deal with undefined arrays, and the spread operator to populate a new array with the two merging arrays. The result array just needs to be sorted and then returned.
const mergeSorted = (a1 = [], a2 = []) => [...a1, ...a2].sort((a, b) => a - b);
Example
const mergeSorted= (a1 = [], a2 = []) => [...a1, ...a2].sort((a, b) => a - b);
console.log(mergeSorted([0, 3, 4, 31], [3, 4, 6, 30]).join(", "));
Or without the sort and using parameter defaults to avoid needing to test arrays for undefined
function mergeSorted(a1 = [], a2 = []) {
const res = [];
var idx1 = 0, idx2 = 0;
while (idx1 < a1.length || idx2 < a2.length) {
if (idx1 < a1.length && idx2 < a2.length) {
res.push(a1[idx1] < a2[idx2] ? a1[idx1++] : a2[idx2++]);
} else {
res.push(idx1 < a1.length ? a1[idx1++] : a2[idx2++]);
}
}
return res;
}
Example
function mergeSorted(a1 = [], a2 = []) {
const res = [], l1 = a1.length, l2 = a2.length;
var i1 = 0, i2 = 0;
while (i1 < l1 || i2 < l2) {
if (i1 < l1 && i2 < l2) { res.push(a1[i1] < a2[i2] ? a1[i1++] : a2[i2++]) }
else { res.push(i1 < l1 ? a1[i1++] : a2[i2++]) }
}
return res;
}
console.log(mergeSorted([0, 3, 4, 31, 99], [3, 4, 6, 30]).join(", "));
In the while condition when i or j indexes reach the length of the corresponding array finishes the loop returning an array of the lower length.
This works:
function mergeTwoSortedArrays(arr1, arr2) {
let merged = [];
let index1 = 0;
let index2 = 0;
let current = 0;
while (current < (arr1.length + arr2.length)) {
let isArr1Depleted = index1 >= arr1.length;
let isArr2Depleted = index2 >= arr2.length;
if (!isArr1Depleted && (isArr2Depleted || (arr1[index1] < arr2[index2]))) {
merged[current] = arr1[index1];
index1++;
} else {
merged[current] = arr2[index2];
index2++;
}
current++;
}
return merged;
}
Fore more info : https://wsvincent.com/javascript-merge-two-sorted-arrays/
In this function I am trying loop into an array, and then return the following thing: if the year is formed by all different digits, then it's a happy year and should be stored where it belongs, in the happy array. If not, it should go in the notHappy array.
Now the problems:
1) The IF condition I tried returns nothing, []. I am quite sure it's not the right way of doing it.
for (var i = 0; i <= t.length; i++) {
if (i[0] != i[1] && i[0] != i[2] && i[0] != i[3]) {
o.happy.push(i++);
} else {
o.notHappy.push(i++)
}
}
2) I tried the same loop with a simple i%2 === 0 condition and I found out that the loop ignores my arr altogether and returns [0, 2, 4] instead of the actual numbers. It's like it would start looping from 0 itself. How come?
function nextHappyYear(arr){
var o = {
happy: [],
notHappy: []
};
var t = arr.map(e => e.toString().split(""));
for (var i = 0; i <= t.length; i++) {
if (i%2 === 0) {
o.happy.push(i++);
} else { o.notHappy.push(i++)}
}
return console.log(o.happy)
}
nextHappyYear([1021, 1022, 1023, 1024]) // returns [0, 2, 4] instead of [1022, 1024]
Your code has some issues
1-for (var i = 0; i <= t.length; i++)
Arrays indexes start from 0 and ends with length - 1. So your condition i <= t.length makes an error. Change it to i < t.length.
2-if (i%2 === 0)
This is not your question condition. You must get all digits in a year and check equality of them.
3-o.happy.push(i++);
This part have 2 problem. First, you push into happy array the index of that year, not the year. Second, i++ increase i by one and one year will get skipped!
4-if (i[0] != i[1] && i[0] != i[2] && i[0] != i[3])
You check just the first digit with others and you don't check second with third and fourth, third digit with forth also.
Try this
function hasDuplicate(arr) {
arr.sort()
for (var i = 0; i < arr.length - 1; i++) {
if (arr[i + 1] == arr[i]) {
return true;
}
}
return false;
}
function happyYear1(arr) {
var o = {
happy: [],
notHappy: []
};
for (var i = 0; i < arr.length; i++) {
if (!hasDuplicate((arr[i] + '').split(""))) {
o.happy.push(arr[i]);
} else {
o.notHappy.push(arr[i]);
}
}
return o;
}
var output = happyYear1([1021, 1022, 1023, 1024]); // returns [0, 2, 4] instead of [1022, 1024]
console.log(output);
var numberArray = [1,2,3,4, 5,6,7,8,9, 9, 4];
var newArray = [];
function primeChecker(arrayCheck){
for (var i = 0; i < arrayCheck.length; i++){
if (Math.sqrt(arrayCheck[i]) % 1 === 0) {
newArray.push(arrayCheck[i]);
}
}
for (var x = 0; x < newArray.length; x++){
newArray.sort();
if (newArray[x] === newArray[x -1]){
newArray.splice(newArray[x-1]);
}
}
}
primeChecker(numberArray);
console.log(newArray);
The returned array is [ 1, 4, 4, 9 ]. The function successfully gets rid of the repeating 9s but I am still left with two 4s. Any thoughts as to why this might be? I am a JavaScript beginner and not totally familiar with the language.
Loop backwards. When you remove the item from the array the array gets shorter.
https://jsfiddle.net/2w0k5tz8/
function remove_duplicates(array_){
var ret_array = new Array();
for (var a = array_.length - 1; a >= 0; a--) {
for (var b = array_.length - 1; b >= 0; b--) {
if(array_[a] == array_[b] && a != b){
delete array_[b];
}
};
if(array_[a] != undefined)
ret_array.push(array_[a]);
};
return ret_array;
}
console.log(remove_duplicates(Array(1,1,1,2,2,2,3,3,3)));
Loop through, remove duplicates, and create a clone array place holder because the array index will not be updated.
Loop backward for better performance ( your loop wont need to keep checking the length of your array)
You do not need insert the number that already is in newArray, you can know what element is in the array with the method indexOf.
Try it in the if, and you can delete the second cicle for.
Something like this:
if (Math.sqrt(arrayCheck[i]) % 1 === 0 && newArray.indexOf(arrayCheck[i])==-1)
This question already has answers here:
Remove duplicate values from JS array [duplicate]
(54 answers)
Closed 8 years ago.
I have the following script that's supposed to uniqualize array:
function uniques(arr) {
var a = [];
for (var i=0, l=arr.length; i<l; i++)
for (var j = 0; j < arr[i].length; j++) {
if (a.indexOf(arr[i][j]) === -1 && arr[i][j] !== '') {
a.push(arr[i][j]);
}
}
return a;
}
However, when it receives only one element, it just breaks it into the letters (which is understandable).
Do you know how I make it check if it's receiving only one element and then returns it back?
Thanks!
I'm not sure why you need the nested loop - you only need a single loop if you're processing a non-nested array:
function uniques(arr) {
if (arr.length === 1) { return arr };
var a = [];
for (var i = 0, l = arr.length; i < l; i++) {
if (a.indexOf(arr[i]) === -1) {
a.push(arr[i]);
}
}
return a;
}
DEMO
If you want to process nested arrays, use a recursive function. Here I've used underscore's flatten method as the basis:
function toType(x) {
return ({}).toString.call(x).match(/\s([a-zA-Z]+)/)[1].toLowerCase();
}
function flatten(input, output) {
if (!output) { output = []; }
for (var i = 0, l = input.length; i < l; i++) {
var value = input[i];
if (toType(value) !== 'array' && output.indexOf(value) === -1) {
output.push(value);
} else {
flatten(value, output);
}
}
return output.sort(function (a, b) { return a - b; });
};
var arr = [1, 2, 3, [[4]], [10], 5, 1, 3];
flatten(arr); // [ 1, 2, 3, 4, 5, 10 ]
DEMO
I think the solution is this:
function uniques(arr) {
if (arr.length > 1) {
var a = [];
for (var i=0, l=arr.length; i<l; i++)
for (var j = 0; j < arr[i].length; j++) {
if (a.indexOf(arr[i][j]) === -1 && arr[i][j] !== '') {
a.push(arr[i][j]);
}
}
return a;
}
else
{
return arr;
}
}
What you're trying to do is a linear search on the created matrix for each item in the original one.
The solution below will accomplish this, but at a great cost. If your original matrix is 50x50 with unique values in each cell, it will take you 50^3 (=125000) loops to exit the function.
The best technique to search, in programming science, takes O(log(N)) that means that if you'll use it on your problem it will take log(50^2) (=11) loops.
function uniques(arr) {
var items = [];
var a = arr.map(function(row, i) {
return row.map(function(cell, j) {
if (items.indexOf(cell) >= 0) {
items.push(cell);
return cell;
}
});
});
}
I have different kind of javascript objects, they all have a property 'row'.
var row1 = {
row: 1
};
var row2 = {
row: 2
};
var row3 = {
row: 3
};
var row4 = {
row: 4
};
...
I have an array defined as follow:
var objArray = [];
In this array it's possible to have multiple 'rows'. The sequence is always te same starting from the lower row to a higher row.
Now I want to get the objects that are linked next to each other (like 4 in a row). In my case it's also possible to have 3 in a row, 5 in a row and so on..
Example:
objArray.push(row0);
objArray.push(row1);
objArray.push(row2);
objArray.push(row3);
objArray.push(row5);
objArray.push(row6);
objArray.push(row7);
objArray.push(row9);
objArray.push(row10);
objArray.push(row12);
In this case I need 2 lists, 1 containing row0 to 3 and one containing 5 to 7.
I've tried a bit in this JSFiddle: Here we can see the console output
If you need more clarification, please ask.
Thanks in advance!
I made a fiddle that does just this for you:
for(var i = 0; i < objArray.length; i++) {
if(currentnum !== -1)
{
var result = objArray[i].row - currentnum;
currentnum = objArray[i].row;
if(result === 1)
{
currentarray.push(objArray[i]);
} else {
arrayofarrays.push(currentarray);
currentarray = [];
currentarray.push(objArray[i]);
}
} else {
currentnum = objArray[i].row;
currentarray.push(objArray[i]);
}
}
arrayofarrays.push(currentarray);
http://jsfiddle.net/B76a8/6/
Since you have already figured how to keep the counter and reset it for each new group you can do
var counter = 1,
lastIndex = 0;
//see chrome dev tools, I need to return objects beginning at the 3rd place untill the 7th place in the array
//how do I get these objects?
for (var i = 0; i < objArray.length; i++) {
if ((i < objArray.length - 1 && objArray[i].row + 1 == objArray[i + 1].row) ||
(i == objArray.length - 1 && objArray[i - 1].row == objArray[i].row - 1)) {
counter++;
} else {
// here we output the grouped items
console.log(objArray.slice(lastIndex, counter+lastIndex));
lastIndex = counter+lastIndex;
counter = 1;
}
}
Demo at http://jsfiddle.net/B76a8/7/
output
[Object { row=0}, Object { row=1}]
[Object { row=3}, Object { row=4}, Object { row=5}, Object { row=6}, Object { row=7}, Object { row=8}]
[Object { row=10}]
First, let's sort the array:
objArray.sort(function(a,b){ return a.row - b.row });
Then, for the given n, this should return you next and previous elements:
function getElement(array, n)
{
var ret = [];
for (var i=0; i<array.length; i++)
if (array[i].row == n)
{
if (i > 0) ret.push(array[i-1]);
if (i < array.length-1) ret.push(array[i+1]);
}
return ret;
}
As getting all the other options with the same color is a different thing let's do it through:
function getByColor(array, color)
{
var ret = [];
for (var i=0; i<array.length; i++)
if (array[i].color == color)
ret.push(array[i]);
return ret;
}
Then you can merge both of the arrays by using concat