What would be a shorter way to write :
if (array1[0] >= array2[0] && array1[1] >= array2[1] && ...) {
do something;
}
I tried creating a function but I was not able to make it work, I'm still quite new at this.
The most elegant way would be to use .every
The every() method tests whether all elements in the array pass the test implemented by the provided function.
if (array1.every(function(e,i){ return e>=array2[i];})) {
do something;
}
This will return true if all elements of a are greater than all elements of b. It will return as early as possible rather than having to compare all of the elements.
function compare(a, b) {
for (i = 0; i < a.length; i++) {
if (a[i] < b[i]) { return false;}
}
return true
}
var isGreater = true;
for (var i = 0; i < array1.length; i++)
{
if (array1[i] < array2[i])
{
isGreater = false;
break;
}
}
if (isGreater)
{
//do something
}
You loop your first array and replace the numbers by the looping variable (i)
Related
I did a exercise in Leetcode, the problem is shown below:
Given a sorted array and a target value, return the index if the
target is found. If not, return the index where it would be if it were
inserted in order.
You may assume no duplicates in the array.
Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0
This is my first try
var searchInsert = function(nums, target) {
if(nums.length === 0){
return -1;
}
var greaterThanPrev = false;
for(var i = 0; i < nums.length; i++){
if(nums[i] === target){
return i;
}else if(nums[i] < target){
greaterThanPrev = true;
}else{
if(greaterThanPrev){
return i;
}
}
}
if(!greaterThanPrev){
return 0
}else{
return nums.length
}
}
Then I think there is no need to iterate all elements in array if the target is greater than current element, so I add a break in the if clause.
var searchInsert = function(nums, target) {
if(nums.length === 0){
return -1;
}
var greaterThanPrev = false;
for(var i = 0; i < nums.length; i++){
if(nums[i] === target){
return i;
}else if(nums[i] < target){
greaterThanPrev = true;
}else{
if(greaterThanPrev){
return i;
}else{
//add this break to avoid iterate all elements in array
break;
}
}
}
if(!greaterThanPrev){
return 0
}else{
return nums.length
}
};
IMO, second solution should be faster than first one, but according by results, the first one is always like 95ms and the solution with break is always more than 120 ms.
Is there any performance issue with keyword break in javascipt?
Regardless of whether it breaks or returns early, I would consider any for loop iterating through an array of numbers O(n). Big O focuses on worst-case analysis and it would be a best-case scenario if the target were less than, or was the first element in the numbers array. This implementation is more minimalistic but also returns early in the for-loop where possible.
function searchInsert(numbers, target) {
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] == target) {
return i;
} else if (numbers[i] > target) {
return i;
}
}
return numbers.length || -1;
}
I have an javascript array and I want to delete an element based on the value of the array, this is my array and this is what I have tried without success.
array = []
array.push (["Mozilla","Firefox",1.10])
index = array.indexOf(["Mozilla","Firefox",1.10])
array.splice(index, 1)
But it doesn't work, any idea¿?
You're trying to compare arrays, which are objects and have unique addresses. Your index variable is -1.
Try ['Mozilla','Firefox',1.10] === ['Mozilla','Firefox',1.10] in your console, you'll see that just because two arrays have the same values, it doesn't mean they are the same array.
What you need is a deep-equals style of comparison, that checks each value in the array, to see if two arrays have a likeness.
Take a look at lodash's isEqual function for an idea.
Here's a simple looping function:
function deepIndex(array, comparison) {
var i, j;
main:
for (i = 0; i < array.length; i++) {
if (Array.isArray(array[i])) {
for (j = 0; j < array[i].length; j++) {
if (array[i][j] !== comparison[j]) {
continue main;
}
}
return i;
}
}
}
var arr = [];
arr.push('string', ['Mozilla','Firefox',1.10], 'thing');
var index = deepIndex(arr, ['Mozilla','Firefox',1.10])
console.log(index, arr);
arr.splice(index, 1);
console.log(arr);
Take a look at this:
// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
This is function, made by the Creator of JQUery.
Basically you take the Index of one thing and than it is getting removed
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
//Equals Function taken from:
//http://stackoverflow.com/questions/7837456/comparing-two-arrays-in-javascript
Array.prototype.equals = function (array) {
// if the other array is a falsy value, return
if (!array)
return false;
// compare lengths - can save a lot of time
if (this.length != array.length)
return false;
for (var i = 0, l=this.length; i < l; i++) {
// Check if we have nested arrays
if (this[i] instanceof Array && array[i] instanceof Array) {
// recurse into the nested arrays
if (!this[i].equals(array[i]))
return false;
}
else if (this[i] != array[i]) {
// Warning - two different object instances will never be equal: {x:20} != {x:20}
return false;
}
}
return true;
}
array = [];
array.push (["Mozilla","Firefox",1.10]);
array.push (["Microsoft","Spartan",1.0]);
array.push (["Safari","Safari",1.4]);
index = indexOfArr(array,["Mozilla","Firefox",1.10]);
array.remove(index, index);
document.getElementById("length").innerHTML = array.length;
for(var i = 0; i < array.length; i++){
document.getElementById("elems").innerHTML += "<br>"+array[i];
}
function indexOfArr(hay, needle){
for(var i = 0; i < hay.length; i++){
if (hay[i].equals(needle)){
return i;
}
}
return -1;
}
<span id = "length"></span><br>
<span id = "elems">Elements:</span>
You can use the fiter metodh, instead of indexOf.
Within the callback of that method, you can choose different approaches:
Use toString on the arrays and compare the two strings
Test for the length and the content, by iterating over the contained elements
... Continue ...
In any case using === will solve the problem, unless the object contained is exactly the same against which you are trying to match.
By the same, I mean the same. We are non speaking about having the same content, but to be the same instance.
Loop over your array and check the equality:
array = [];
array.push(["Mozilla", "Firefox", 1.10]);
for (var i = 0; i < array.length; i++) {
if (arraysEqual(array[i], ["Mozilla", "Firefox", 1.10])) {
array.splice(i, 1);
}
}
function arraysEqual(a, b) {
if (a === b) return true;
if (a === null || b === null) return false;
if (a.length != b.length) return false;
for (var i = 0; i < a.length; ++i) {
if (a[i] !== b[i]) return false;
}
return true;
}
JSFiddle: http://jsfiddle.net/ghorg12110/r67jts35/
Based on this question : How to check if two arrays are equal with JavaScript?
You can do something like this
array = []
array.push (["Mozilla","Firefox",1.10])
tempArray = array[0];
index = tempArray.indexOf("Mozilla","Firefox",1.10)
array.splice(index, 1)
You can build on this if you put for loop instead of hard coding.
I have an array with boolean values:
var array = [false, false, false];
I want to execute a function only if all the elements are false.
I tried this and it didn't work, because it would execute the function for every false:
for(var i = 0; i < array.length; i++){
if(array[i] === false){
functionA(); //This function ran at every false
}else{
//Do something else
}
}
if (array.indexOf(true) == -1) {
functionA();
}
The indexOf function returns the first index at which a given element can be found in the array, or -1 if it is not present.
You could do something like:
function checkAllSameValue(array) {
var identical = true;
var i = 0;
while ((i + 1) in array && identical) {
identical = array[i] == array[++i];
}
return identical;
}
Which checks if each member is identical to the next
Edit
In response to ilia choly's issues with performance and lookups, here's an alternative that is as fast as a for loop, perhaps faster depending on the UA:
function checkAllSameValue(array) {
var i = array.length;
var value = array[--i];
while (i) {
if (arr[--i] != value) return false
}
return true;
}
Whether == or === should be used is up to the OP. None of the posted solutions deals with sparse arrays, so none are general solutions.
Gues this will help:
var array = [false, false, false];
var flag = true;
for(var i = 0; i < array.length; i++){
if(array[i]!= false){
flag = false;
break;
}
}
if(flag){
functionA(); //This function call function only once
}
The way you describe it is slightly different from the title. If you're only trying to execute the function if they are all false, then Steve's answer is great. Depending on where this array comes from, I would probably expand it like so, though, to be defensive about it:
if (array.indexOf(true) == -1 && array.indexOf(null) == -1) {
functionA();
}
OTOH, if you want to run it any time they are all the same, then you'll need more complex logic.
In that case, I would probably set a flag, update it in the loop, and then do the function call after the loop. You'll also need a variable to keep track of the previous value. If any value doesn't match its previous value, they're not all the same, so you set the flag to false. Then, after the loop, you check the flag and run the function if it's true.
Something like this:
var runFunction = true;
var previousVal = -1;
for (var i = 0; i < array.length; i++){
if(previousVal === -1) {
previousVal = array[i];
}
if(array[i] !== previousVal){
runFunction = false;
break;
}
}
if (runFunction) {
functionA();
} else {
// Do something else
}
Steve's way is better, but if you were going to use your approach it would be
var allFalse = true, i;
for(i = 0; i < array.length; i++) {
if(array[i]){
allFalse = false;
break;
}
}
if (allFalse) {
functionA();
}
or
if (array.every(function(val) { return !val; })) {
functionA();
}
if you want a generic function to check if all elements are the same you can do this
function checkAllSameValue(array) {
var first = array[0], i;
for (i = 1; i < array.length; i++) {
if (array[i] !== first) return false;
}
return true;
}
I have two arrays of integers a=[1,3,5,7] and b=[2,4,6,8].
Now I need to check if a given var $v is in a and if it is, return the equivalent element from b. Example:
if $v in a (and $x is its position) return $b[$x].
How do I perform this?
the indexOf method will return the index of the array where the item was found, or -1 if it wasn't found.
var i = a.indexOf(v);
if (i != -1)
{
return b[i]
}
EDIT: This will add the method if your browser doesn't have it.
if (!Array.prototype.indexOf)
{
Array.prototype.indexOf = function(x)
{
var i;
for (i = 0; i < this.length; i++)
{
if (this[i] === x)
{
return i;
}
}
return -1;
}
}
Loop through the items in the array:
for (var i = 0; i < a.length; i++) {
if (a[i] == v) {
return b[i];
}
}
return -1; // not found
var i = a.indexOf(v);
if (i !== -1)
{
return b[i]
}
if(a.indexOf(v) > -1) {
var id = a.indexOf(v);
console.log(b[id]);
}
See for compatibility of Array.indexOf
I suppose this would work.
>> function test(k){ return b[a.indexOf(k)]}
>> test(1)
2
>> test(9)
undefined
In js, indexOf always returns an integer and by calling an array with an integer (like A[3] ), it always returns a value or undefined. explicitly check for the undefined value if you want to make sure application code is not broken.
You may want to give below function a try. PHP.js is really a great collection of functions and salute to all contributors to make it what it is today.
http://phpjs.org/functions/in_array:432
I have a javascript array of Date objects, which I'd like to test for ascendingness. This is what I built, but I am kind of disappointed by it. Any suggestion?
function isAscending(timeLine) {
if (timeLine.length < 2)
return true;
for(var i=1; i < timeLine.length; i++) {
if(timeLine[i-1] > timeLine[i])
return false;
}
return true;
}
(I was hoping for something more expressive, built-in, some library math function etc.)
That's the simplest way to do it; don't be disappointed.
How about
function isAscending(timeLine){
var i=0, L= timeLine.length-1;
while(i<L){
if(timeLine[i]> timeLine[++i]) return false;
}
return true;
}
es6 way
let isAscending = timeLine =>
timeLine.every( (v, i, a) => a.length - 1 === i || v < a[i + 1] )