javascript check if array contains multiple elements in a row - javascript

I would like to know if its possible to search an array for multiple items which are in a row, something similar to below. I have done it with separate includes, but this does not allow me to tell if the elements are in a row or near each other.
The array is not sorted and the numbers have to be in a defined order. Near being in a row, specifically 3. So (23,34,45) being searched within (12,23,45,34) would be false.
Thanks
var num = [];
num.push(12,23,34,45,56,67,78,89,90);
if(num.includes(23,34,45)){
print('found');
}

One more way using ES6 Set() feature:
var arr = [12,23,34,12,45,56,67,78,89,90];
var set = new Set();
arr.forEach(function(i){ set.add(i) });
var foundCount = 0;
var func = function(a){
a.forEach(function(item) {
var oldLength = set.size;
set.add(item);
var newLength = set.size;
if(oldLength === newLength) {
foundCount++;
}
});
console.log('found ' + foundCount)
}
var arr2 = [12, 34, 45];
func(arr2);

This works, I hope I understood your question correctly.
function foo(num1, num2, num3, arr) {
var exists = false;
for(var i = 0; i < arr.length; i++) {
if(arr[i] == num1 && arr[i+1] == num2 && arr[i+2] == num3) {
exists = true;
}
}
console.log(exists);
}
var array = [12,23,34,45,56,67,78,89,90];
foo(23,34,45,array);

Related

Selecting a random amount of elements from array in javascript

I have 2 arrays with 4 x-coordinates in each. In total I want to select 3 random values from both arrays. So array1+array2 =3 elements. In the end i just done it a bad way to make it do what i wanted. Just wondering if anyone can see a more efficient way to produce nicer code. This is how i ended up getting it to work. I cant show what i have tried as it has been so modified i ended up just deleting it and doing this.
enemyCars = [100, 200, 300, 400]; //not actual values
newCarArray = []; //global
newWallArray = []; //global
function randomNumber(a, b){
return Math.round(random(a,b));
}
function chooseCars(){
let carAmount = randomNumber(0,3);
let wallAmount = 3 - carAmount;
print('carAmount ' + carAmount);
if(carAmount == 0){
newCarArray = [];
}
if(carAmount == 1){
let a = randomNumber(0,3);
newCarArray.push(enemyCars[a]);
}
if(carAmount == 2){
let a = randomNumber(0,3);
newCarArray.push(enemyCars[a]);
let b = randomNumber(0,3);
newCarArray.push(enemyCars[b]);
}
if(carAmount == 3){
let a = randomNumber(0,3);
newCarArray.push(enemyCars[a]);
let b = randomNumber(0,3);
newCarArray.push(enemyCars[b]);
let c = randomNumber(0,3);
newCarArray.push(enemyCars[c]);
}
if(wallAmount == 0){
newWallArray = [];
}
if(wallAmount == 1){
let a = randomNumber(0,3);
newWallArray.push(enemyWalls[a]);
}
if(wallAmount == 2){
let a = randomNumber(0,3);
newWallArray.push(enemyWalls[a]);
let b = randomNumber(0,3);
newWallArray.push(enemyWalls[b]);
}
if(wallAmount == 3){
let a = randomNumber(0,3);
newWallArray.push(enemyWalls[a]);
let b = randomNumber(0,3);
newWallArray.push(enemyWalls[b]);
let c = randomNumber(0,3);
newWallArray.push(enemyWalls[c]);
}
}
thanks for the help
Thanks for the help I was finally able to create some nicer code. always seem to overcomplicate things and can't see the simple solution. Thanks #JonasWilms
function abc(){
let carAmount = randomNumber(0,3);
let wallAmount = 3 - carAmount;
print('carAmount ' + carAmount);
print('wallAmount ' + wallAmount);
let enemyCoord = [...enemyCars];
//print(enemyCoord);
newCarArray = [];
newWallArray = [];
for(let i = 0; i < carAmount; i++) {
let a = randomNumber(0,enemyCoord.length-1)
newCarArray.push(enemyCars[a]);
delete enemyCoord[a];
filterArray(enemyCoord);
}
for(let i = 0; i <wallAmount; i++){
let a = randomNumber(0,enemyCoord.length-1)
newWallArray.push(enemyWalls[a]);
delete enemyCoord[a];
filterArray(enemyCoord);
}
print(newCarArray);
print(newWallArray);
}
Here's a short code that merges two arrays into a single array, shuffles it randomly, and then give you the first three values from the array:
var randoms = randoSequence([1, 2, 3, 4].concat([5, 6, 7, 8])).splice(0, 3)
randoms.forEach(function(p, i, a){a[i]=a[i]["value"]});
console.log(randoms);
<script src="https://randojs.com/1.0.0.js"></script>
Notice the second line. https://randojs.com gives you an array of objects with BOTH indices and values, but we're only interested in the values.
All you need is a loop:
for(let count = 0; count < carAmount; count++) {
newCarArray.push(enemyCars[ randomNumber(0, 3) ]);
}

Create Array From List of data

Hi First time Post here , please do forgive my poor English.
I have a list of data as follow
var list = '1,2,3,4,8,9,10,20,21,22,23,24'
i would like to convert this list to array, something like this
var array = ([1,4],[8,10],[20,24]);
Which it will take the first and the last(1-4) element of the list before it jump to another variable(8-10).
I have come out with some code but it's very messy
var first = true;
var firstvalue = '';
var b ='';
var endvalue ='';
var last = '';
var myArray = [];
$('.highlight').each(function() {//Loop in list
if(first){//Only For the first time to set up the loop
firstvalue = this.id;
b = firstvalue;
first = false;
return;
}
if(parseInt(this.id)-1 != b){//When gap happen and new array is insert
endvalue = b;
/*save here*/
myArray.push([firstvalue,endvalue]);
firstvalue = this.id;
b = firstvalue;
}else{
b = this.id;
}
last = this.id;//Last Item that cant capture
});
myArray.push([firstvalue,last]);
Are there any better way for this ?
Try this: easy and simple method.
var list = '1,2,3,4,8,9,10,20,21,22,23,24';
list = list.split(',');
var arrayList = [];
var firstEle = 0, lastEle = 0;
list[-1] = -2;
for(var i=-1; i<list.length; i++)
{
if(i == 0)
firstEle = list[0];
if(((list[i+1] - list[i]) > 1) && i >= 0 && i <= (list.length - 1))
{
lastEle = list[i];
arrayList.push('['+firstEle+','+lastEle+']');
firstEle = list[i+1];
}
else if(i == (list.length - 1))
{
lastEle = list[i];
arrayList.push('['+firstEle+','+lastEle+']');
}
}
alert(arrayList);
Try that:
var list = '1,2,3,4,8,9,10,20,21,22,23,24,26,27,28,30';
list = list.split(',').map(x => parseInt(x));
list.push(Infinity);
console.log(JSON.stringify(list));
var startIndex = 0;
var result = list.reduce((a, b, i, arr) => {
if(i != 0 && b - 1 != arr[i-1])
{
a.push([arr[startIndex], arr[i-1]]);
startIndex = i;
}
return a;
}, []);
console.log(JSON.stringify(result));
You could split the string and convert all values to number. Then use Array#reduce with the generated array and check the predecessor and the actual value.
If unequal with the incremented predeccessor, then concat a new array with the actual value to the result set.
Otherwise update the value at index 1 of the last array in the result set.
It works for any range sizes.
var list = '1,2,3,4,8,9,10,20,21,22,23,24',
result = list.split(',').map(Number).reduce(function (r, a, i, aa) {
if (aa[i - 1] + 1 !== a) {
return r.concat([[a]]);
}
r[r.length - 1][1] = a;
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
you can do this
var result=[];
var list = '1,2,3,4,8,9,10,20,21,22,23,24'
var dataOflist=list.split(',');
var l=dataOflist.splice(dataOflist.length-4,4);
var f=dataOflist.splice(0,4);
result[0]=f;
result[1]=dataOflist;
result[2]=l;
console.log(result);
hope this help

Javascript: Write a function that takes in an array, and then returns an array with only unique numbers, only arrays removed

Write a function that takes in a list and returns a list with all of the duplicates removed (list will only have unique numbers).
Here's what I have so far:
var lista = [1,4,5,1,1,3,5,6,4,4,3];
function dupRemove (lista) {
//Sort the array in case it isn't sorted
lista.sort();
//Object to store duplicates and unique numbers
var listNumbers = {
"Duplicate Numbers": [],
"Unique Numbers": []
};
for (var i = 0; i < lista.length; i++) {
//check if it is not equal to the index of the array before it and after. if it isn't, that means its unique, push it in the uniques array.
if (lista[i] !== lista[i-1] && lista[i] !== lista[i+1]) {
listNumbers["Unique Numbers"].push(lista[i]);
} else {
listNumbers["Duplicate Numbers"].push(lista[i]);
}
}
return listNumbers;
}
Currently, my solution returns an object with keys with the values of "Duplicates": 1, 1, 1, 3, 3, 4, 4, 4, 5, 5 and "Uniques": 6.
How do I remove the duplicates from duplicates and then join these two keys into a single array?
Thank you.
that answer is seriously over -engineered- all you need to to is push all values into a new array if they are not already in it.
function=removeDups()
{
var lista = [1,4,5,1,1,3,5,6,4,4,3];
var uniqueValues=[];
var duplicateValues=[];
for(i=0;i<lista.length;i++)
{
if(uniqueValues.indexof(lista[i] == -1){uniqueValues.push(lista[i]}else{duplicateValues.push(lista[i]}
}
}
You could just use the default filter method that is on all Arrays
You don't need the sort function either. If the item is already found using the indexOf method it will not be added to the newly returned array created by the filter method
var list = [1,4,5,1,1,3,5,6,4,4,3];
function removeDup (arr) {
return arr.filter(function(item, pos) {
return arr.indexOf(item) == pos;
})
}
var sortedList = removeDup(list).sort(function(a,b){
return a - b
})
document.getElementsByTagName('div')[0].textContent = sortedList
<div></div>
Kind of a non elegant solution but it gives you the two arrays: one with the duplicate values and one with the unique ones. Since you cannot rely on .sort() you can just count things.
Function checkList will give you back those two arrays.
var list = [1,4,5,1,1,3,5,6,4,4,3];
console.log(checkList(list));
function checkList(list) {
var uniques = []; // will be [6]
var dups = []; // will be [1, 4, 5, 3]
var checked = []; // save what you have already checked so far
for(i = 0; i < list.length; i++) {
if(notChecked(list[i], checked)) {
checked.push(list[i]);
if(count(list[i], list) > 1) {
dups.push(list[i]);
} else {
uniques.push(list[i]);
}
}
}
return {dups: dups, uniques: uniques}
}
// count how many num in arr
function count(num, arr) {
var count = 0;
var i;
for(i = 0; i < arr.length; i++) {
if(arr[i] == num) count++;
if(count > 1) return count;
}
return count;
}
// check if num has not been checked
function notChecked(num, arr) {
return (arr.indexOf(num) == -1) ? true : false;
}

add elements of an array javascript

Ok, this might be easy for some genius out there but I'm struggling...
This is for a project I'm working on with a slider, I want an array the slider can use for snap points/increments... I'm probably going about this in a mental way but its all good practice! Please help.
var frootVals = [1,2,3,4,5];
var frootInc = [];
for (i=0; i<=frootVals.length; i++) {
if (i == 0){
frootInc.push(frootVals[i]);
}
else{
frootInc.push(frootInc[i-1] += frootVals[i])
}
};
What I'm trying to do is create the new array so that its values are totals of the array elements in frootVals.
The result I'm looking for would be this:
fruitInc = [1,3,6,10,15]
For a different take, I like the functional approach:
var frootVals = [1,2,3,4,5];
var frootInc = [];
var acc = 0;
frootVals.forEach(function(i) {
acc = acc + i;
frootInc.push(acc);
});
var frootVals = [1,2,3,4,5]
, frootInc = [];
// while i < length, <= will give us NaN for last iteration
for ( i = 0; i < frootVals.length; i++) {
if (i == 0) {
frootInc.push(frootVals[i]);
} else {
// rather than frootIne[ i-1 ] += ,
// we will just add both integers and push the value
frootInc.push( frootInc[ i-1 ] + frootVals[ i ] )
}
};
There were a few things wrong with your code check out the commenting in my code example. Hope it helps,
This will do:
var frootVals = [1,2,3,4,5];
var frootInc = [];
for (i=0; i < frootVals.length; i++) { // inferior to the length of the array to avoid iterating 6 times
if (i == 0) {
frootInc.push(frootVals[i]);
}
else {
frootInc.push(frootInc[i-1] + frootVals[i]) // we add the value, we don't reassign values
}
};
alert(JSON.stringify(frootInc));
jsfiddle here: http://jsfiddle.net/f01yceo4/
change your code to:
var frootVals = [1,2,3,4,5];
var frootInc = [frootvals[0]]; //array with first item of 'frootVals' array
for (i=1; i<frootVals.length; i++) {
frootInc.push(frootInc[i-1] + frootVals[i]); //remove '='
}
Here's a very simple pure functional approach (no vars, side-effects, or closures needed):
[1,2,3,4,5].map(function(a){return this[0]+=a;}, [0]);
// == [1, 3, 6, 10, 15]
if you name and un-sandwich the function, you can use it over and over again, unlike a hard-coded var name, property name, or for-loop...

How do I know an array contains all zero(0) in Javascript

I have an array. I need to generate an alert if all the array items are 0.
For example,
if myArray = [0,0,0,0];
then alert('all zero');
else
alert('all are not zero');
Thanks.
You can use either Array.prototype.every or Array.prototype.some.
Array.prototype.every
With every, you are going to check every array position and check it to be zero:
const arr = [0,0,0,0];
const isAllZero = arr.every(item => item === 0);
This has the advantage of being very clear and easy to understand, but it needs to iterate over the whole array to return the result.
Array.prototype.some
If, instead, we inverse the question, and we ask "does this array contain anything different than zero?" then we can use some:
const arr = [0,0,0,0];
const someIsNotZero = arr.some(item => item !== 0);
const isAllZero = !someIsNotZero; // <= this is your result
This has the advantage of not needing to check the whole array, since, as soon it finds a non-zero value, it will instantly return the result.
for loop
If you don't have access to modern JavaScript, you can use a for loop:
var isAllZero = true;
for(i = 0; i < myArray.length; ++i) {
if(myArray[i] !== 0) {
isAllZero = false;
break;
}
}
// `isAllZero` contains your result
RegExp
If you want a non-loop solution, based on the not-working one of #epascarello:
var arr = [0,0,0,"",0],
arrj = arr.join('');
if((/[^0]/).exec(arrj) || arr.length != arrj.length){
alert('all are not zero');
} else {
alert('all zero');
}
This will return "all zero" if the array contains only 0
Using ECMA5 every
function zeroTest(element) {
return element === 0;
}
var array = [0, 0, 0, 0];
var allZeros = array.every(zeroTest);
console.log(allZeros);
array = [0, 0, 0, 1];
allZeros = array.every(zeroTest);
console.log(allZeros);
Use an early return instead of 2, 3 jumps. This will reduce the complexity. Also we can avoid initialisation of a temp variable.
function ifAnyNonZero (array) {
for(var i = 0; i < array.length; ++i) {
if(array[i] !== 0) {
return true;
}
}
return false;
}
Using Math.max when you know for certain that no negative values will be present in the array:
const zeros = [0, 0, 0, 0];
Math.max(...zeros) === 0; // true
No need to loop, simple join and reg expression will work.
var arr = [0,0,0,10,0];
if((/[^0]/).exec(arr.join(""))){
console.log("non zero");
} else {
console.log("I am full of zeros!");
}
Another slow way of doing it, but just for fun.
var arr = [0,0,0,0,10,0,0];
var temp = arr.slice(0).sort();
var isAllZeros = temp[0]===0 && temp[temp.length-1]===0;
you can give a try to this :
var arr = [0,0,0,0,0];
arr = arr.filter(function(n) {return n;});
if(arr.length>0) console.log('Non Zero');
else console.log("All Zero");

Categories

Resources