Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I have started learning Javascript and is doing some simple exercises. Given an array of numbers, return uneven numbers. I Have used both the "Classical" way of doing it as well as an arrow function. However they are acting a bit weird. This is the arrow function:
const answer2 = [1, 2, 3, 4, 5, 6, 7, 8, 9].filter(value => {
return value % 2 != 0;
})
It looks alright to me and it seems to work. Then I did the classical one:
function filterArrayToOdd(inputArray) {
let outputArray = [];
for (let i = 0; i < inputArray.length; i++) {
if (i % 2 != 0) {
outputArray.push(inputArray[i]);
}
}
return outputArray;
}
This returns an array with all the even numbers! Changing the comparrison from != to == works, but why?!
It would be better if your test array was not in sequence, [1, 2, 3, 4, 5, 6, 7, 8, 9], but rather something like, [2, 5, 9, 11, 12, 3].
In sequence, you can produce false positives to this problem, because, as #Pointy is saying, in your second case, you are checking your array index, not the actual value.
// instead of
if (i % 2 != 0) {
// do this:
if (inputArray[i] % 2 != 0) {
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
How do I compare elements in an array using Javascript?
I want to know if cas[1], cas[2] and cas[3] have the same value.
cas = ["0","1", "2","3","4","5","6","7","8","9"];
if(cas[1]== cas[2] && cas[2]==cas[3]){
console.log("yea");
}
The first of all it's better to use ===, because 0 == false is true, but 0 === false is false.
=== works without type casting.
You don't need full cycle loop here, you have to compare only the first 3 elements so if statement is ok here.
If you want to do that with every 3 elements, you can do something like this.
const getThreeArrayElements = (array, startIndex) => array.slice(startIndex, startIndex + 3);
getThreeArrayElements([1, 2, 3, 3, 3, 3], 0); // [1, 2, 3]
getThreeArrayElements([1, 2, 3, 3, 3, 3], 3); // [3, 3, 3]
So you can easily get an array with 3 required elements.
The another task is how to compare them.
const areArrayElementsEqual = array => array.every(item => item === array[0]);
areArrayElementsEqual([1, 2, 3]); // false
areArrayElementsEqual([3, 3, 3]); // true
if you're looking for an algorithm to check the entire array :
let cas = ["0","1", "2","3","4","5","6","7","8","9"];
let checkCas = (cur = 1)=>{return cas[cur-1]===cas[cur]?true:cur<cas.length?checkCas(++cur):false;};
console.log(checkCas());
cas = ["0","1", "2","3","4","5","5","7","8","9"];
console.log(checkCas());
as for ticktacktoe :
let casa = ["0","1", "2","3","4","5","6","7","8","9"];
let allEqual = (cas,cur = 1)=>{return cas[cur-1]===cas[cur]?true:cur<cas.length?allEqual(cas,++cur):false;};
for(let i = 0;i<Math.floor(casa.length/3);i++)
{
let tempLengArr = [casa[i],casa[i+3],casa[i+6]];
if(allEqual(casa.slice(i*3,(i*3)+3))||allEqual(tempLengArr))
console.log("won");
}
if(allEqual([casa[0],casa[4],casa[9]])||
allEqual([casa[3],casa[4],casa[2]])) console.log("won");
might have messed up a bit on my allEqual call but it's an idea
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
Given a sorted array of numbers, how do you get ranges of consecutive numbers? The function should return ranges and single numbers as a string. Example:
function findRanges(arrayOfSortedNumbers) {
// logic here
}
findRanges([1, 3, 4, 5, 7]) => (expected output: "1, 3-5, 7")
findRanges([1, 2, 3, 5]) => (expected output: "1-3, 5")
findRanges([2, 3, 4, 5, 6]) => (expected output: "2-6")
Sorry for not being able to explain the problem better.
You can use Array.reduce() to do it:
Sort the array (safety)
Iterate over the array with reduce to create an object containing the ranges and the start of the active range (rangeStart).
On the first iteration, push the first element in the ranges and save this element as the rangeStart
On the successive iterations, if the value equals the last value + 1, we are in the same range, so we update it by changing the last value in the ranges array. Otherwise, we push the element in the ranges array and update rangeStart to be this element.
Return the ranges property of the object output by reduce and join it using commas.
function findRanges(numbers) {
return [...numbers].sort((a, b) => a - b).reduce((acc, x, i) => {
if (i === 0) {
acc.ranges.push(x);
acc.rangeStart = x;
} else {
if (x === acc.last + 1) {
acc.ranges[acc.ranges.length-1] = acc.rangeStart + '-' + x;
} else {
acc.ranges.push(x);
acc.rangeStart = x;
}
}
acc.last = x;
return acc;
}, { ranges: [] }).ranges.join(', ');
}
console.log(findRanges([1, 3, 4, 5, 7]));
console.log(findRanges([1, 2, 3, 5]));
console.log(findRanges([2, 3, 4, 5, 6]));
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I am following the official React tutorial, which describes a helper function that checks for a winning combination for a Noughts & Crossesgame (Tic-tac-toe).
It does this by checking for the presence of a winning combination in a components state, and either returns the winning X/O or null object:
//Board component
return{
const winner = calculateWinner(this.state.squares);
}
//helper function
function calculateWinner(squares) {
const lines = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6],
];
for (let i = 0; i < lines.length; i++) {
const [a, b, c] = lines[i];
if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
return squares[a];
}
}
return null;
}
https://reactjs.org/tutorial/tutorial.html#declaring-a-winner
My question: what is the rational be for making calculateWinner() a helper function and not a method on the Board component or a functional component?
Is it due to the separation on concerns i.e. the function does not directly affect the UI?
Is it due to the separation on concerns?
Yes. It makes no sense to have that function as a method on Board, as it is not accessing the board in any way.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Say you have a list of numbers:
var list = [4, -12, 18, 1, -3];
What is a more elegant solution to finding the value closest to zero without nesting a whole lot of if/else statements?
use reduce:
list.reduce((pre,cur) => Math.abs(pre) > Math.abs(cur) ? cur : pre)
This is what you could do with a single traversal of the array.
function findClosestToZero(arr) {
if (arr.length === 0) {
return;
}
var closeNumber = Math.abs(arr[0]);
arr.forEach(function(number) {
if (Math.abs(number) < closeNumber) {
closeNumber = Math.abs(number)
}
});
return closeNumber;
}
var arr = [-5, 98, -4, 7, 9, 213, 4, -2, 1];
console.log(findClosestToZero(arr));
use sort :
list.sort((a,b) => Math.abs(a)-Math.abs(b))[0];
get the absolute value of all numbers
Math.abs()
sort the number in ascending order
Array.sort()
The first number is the required answer.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Its kinda weird that the JavaScript Array class does not offer a last method to retrieve the last element of an array. I know the solution is simple (Ar[Ar.length-1] ), but, still, this is too frequently used.
Any serious reasons why this is not incorporated yet?
You can do something like this:
[10, 20, 30, 40].slice(-1)[0]
console.log([10, 20, 30, 40].slice(-1)[0])
The amount of helper methods that can be added to a language is infinite. I suppose they just haven't considered adding this one.
It's easy to define one yourself. That's the power of JavaScript.
if(!Array.prototype.last) {
Array.prototype.last = function() {
return this[this.length - 1];
}
}
var arr = [1, 2, 5];
arr.last(); // 5
However, this may cause problems with 3rd-party code which (incorrectly) uses for..in loops to iterate over arrays.
However, if you are not bound with browser support problems, then using the new ES5 syntax to define properties can solve that issue, by making the function non-enumerable, like so:
Object.defineProperty(Array.prototype, 'last', {
enumerable: false,
configurable: true,
get: function() {
return this[this.length - 1];
},
set: undefined
});
var arr = [1, 2, 5];
arr.last; // 5
Because Javascript changes very slowly. And that's because people upgrade browsers slowly.
Many Javascript libraries implement their own last() function. Use one!
i = [].concat(loves).pop(); //corn
icon cat loves popcorn
Another option, especially if you're already using UnderscoreJS, would be:
_.last([1, 2, 3, 4]); // Will return 4
Array.prototype.last = Array.prototype.last || function() {
var l = this.length;
return this[l-1];
}
x = [1,2];
alert( x.last() )
Came here looking for an answer to this question myself. The slice answer is probably best, but I went ahead and created a "last" function just to practice extending prototypes, so I thought I would go ahead and share it. It has the added benefit over some other ones of letting you optionally count backwards through the array, and pull out, say, the second to last or third to last item. If you don't specify a count it just defaults to 1 and pulls out the last item.
Array.prototype.last = Array.prototype.last || function(count) {
count = count || 1;
var length = this.length;
if (count <= length) {
return this[length - count];
} else {
return null;
}
};
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
arr.last(); // returns 9
arr.last(4); // returns 6
arr.last(9); // returns 1
arr.last(10); // returns null
Here is another simpler way to slice last elements
var tags = [1, 2, 3, "foo", "bar", "foobar", "barfoo"];
var lastObj = tags.slice(-1);
lastObj is now ["barfoo"].
Python does this the same way and when I tried using JS it worked out. I am guessing string manipulation in scripting languages work the same way.
Similarly, if you want the last two objects in a array,
var lastTwoObj = tags.slice(-2)
will give you ["foobar", "barfoo"] and so on.
pop() method will pop the last value out. But the problem is that you will lose the last value in the array
Yeah, or just:
var arr = [1, 2, 5];
arr.reverse()[0]
if you want the value, and not a new list.