Check if an element already exist in an array in javascript [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I have the following array
array =[['apple',23,1,20],['orange',12,10,10]]
How do i check if 10 exist in the above array ?I tried to use array.indexOf but it did not work well.Can someone help ?

.indexOf() will work, the problem is with the array variable.
array variable itself contains 2 different arrays.
Try the below code.
var array = [
['apple', 23, 1, 20],
['orange', 12, 10, 10]
];
for (var i = 0; i < array.length; i++) { //Iterate through arrays in array
if (array[i].indexOf(10) > -1) {
alert("Yep");
} else {
alert("nope");
}
}
Check this JSFiddle

in ECMAScript 5 , there are two array methods some and indexOf
var search = 10 ;
var found = a.some( function( v ) {
return v.indexOf( search ) !== -1 ;
});
if ( found ) {
alert( 'exists')
}

The problem may be because:
you have nested arrays
Array.indexOf is not supported by all browsers
The following should work:
function includes(arrayOfArrays, item) {
var array, i, j;
for(i=0; i<arrayOfArrays.length; ++i) {
array = arrayOfArrays[i];
for(j=0; j<array.length; ++j) {
if(array[j] === item) {
return true;
}
}
}
return false;
}

You can use following code to search in the array.
<!DOCTYPE html>
<html>
<body>
<script>
var i,j;
var toFind = 10;
var array = new Array();
array = [['apple',23,1,20],['orange',12,10,10]]
for (i=0;i<array.length;i++)
{
for(j=0;j<array[i].length;j++)
{
if(array[i][j] == toFind)
document.write("element found <br/>");
}
}
</script>
</body>
</html>
where toFind is the element or number that you want to find.

Related

Make all numbers in array Absolute value in Javascript [closed]

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 2 years ago.
Improve this question
I'm trying to make all values in the below array absolute, after trying several methods the results that appears is 5 the first element in the array. the below is the code given:
describe('absoluteValueArray', () => {
it('Gets multiple absolute values', () => {
const result = absoluteValueArray([-5,-50,-25,-568])
expect(result).toEqual([5,50,25,568])
})
})
Function I tried is the below:
const absoluteValueArray = (array) => {
var index, len;
var array = ["-5", "-50", "-25" , "-568"];
for (index = 0, len = array.length; index < len; ++index) {
let res = Math.abs(array[index]);
return res;
}
}
You approach does not work in this line and the next
let res = Math.abs(array[index]);
return res;
because you need to assign the absolute value to the array or a new array at the same index, like
resultArray[i] = Math.abs(array[index]);
and return the array after finishing the loop.
The original return inside of the loop exits the loop with the first element.
Instead, you could take Math.abs as callback for Array#map.
const absoluteValueArray = (array) => {
return array.map(Math.abs);
}
console.log(absoluteValueArray([-5, -50, -25, -568]));

Adding values to an array in JavaScript loops [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I'm learning JavaScript and I used the loops to add some values to an array and then print theme and see the result. I have done this with different methods but I have a problem with one of them.
In the code below I can't think of a way to add values to an array using for/in the loop. How can I do this?
<script type="text/javascript">
function print(string){
document.write(string+"<br>");
}
</script>
<script type="text/javascript">
print("with for & for..in");
var ma1Arr = [];
for (i = 10; i < 20; i++) {
ma1Arr.push(i);
}
for (i in ma1Arr) {
print(ma1Arr[i]);
}
print("<hr>");
print("with for & for..in vice versa");
var ma3Arr = [];
i=20;
for (i in ma3Arr){
ma3Arr.push(i);
i++
}
for (i=0; i<ma3Arr.length; i++){
print(ma3Arr[i])
}
print("<hr>");
print("with while & do..while");
var ma2Arr = [];
i = 30;
do {
ma2Arr.push(i);
i++;
} while (i < 40);
i = 0;
while (i < ma2Arr.length) {
print(ma2Arr[i]);
i++;
}
print("<hr>");
print("with while & do..while vice versa");
var ma4Arr = [];
i = 40;
while (i<=50){
ma4Arr.push(i);
i++;
}
i = 0
do {
print(ma4Arr[i]);
i++;
}while (i<ma4Arr.length);
</script>
for...in is used for objects like {a: 1, b: 4} and not for arrays. It is iterating all enumerable properties of the object such as a and b. But for arrays, you would need to go with for...of
for..in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
for...of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of
var array_name = [item1, item2, ...];
You put the values inside of the brackets... That is basically how you make an array for any language

JavaScript array push not working [closed]

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 7 years ago.
Improve this question
I am trying to push a value into an array and it is giving me this error in the developer tools.
Uncaught TypeError: Cannot read property 'push' of null
Here is the code that it seems to be sticking on, word and local word were defined earlier like this.
var word = [];
var localWord = [];
function setLocalArray() {
// first get words from text field and update word array.
word = document.getElementById("words").value.split(',');
// store word array in localStorage
for(var i=0; word.length > i; i++) {
var key2 = "part"+i;
localStorage.setItem(key2,word[i]);
localWord.push(key2);
}
localStorage.setItem("localWord",JSON.stringify(localWord));
text2Array();
reveal();
}
localWord.push(key2); Seems to be what it is getting stuck on. I have looked at everything I can find on the push method and I can't seem to find why it is giving me this error. Help?
Here is the full code at jsfiddle http://jsfiddle.net/runningman24/jnLtpb6y/
Try this...
var localWord = new Array(); //create new array
var word = new Array();
function setLocalArray() {
word = document.getElementById("words").value.split(',');
// store word array in localStorage
for(var i=0; word.length > i; i++) {
var key2 = "part"+i;
localStorage.setItem(key2,word[i]);
localWord.push(key2);
}
}
I found the problem, if you look in the jsfiddle I posted I am trying to pull localWord from localStorage even though it doesn't exist and so it sets it to null. Thank you to all for the ideas and contributions.
You could try isolating the scope of your variable using the module pattern:
var arrayManager = (function () {
var word = [];
var localWord = [];
function setLocalArray() {
// first get words from text field and update word array.
word = document.getElementById("words").value.split(',');
// store word array in localStorage
for(var i=0; word.length > i; i++) {
var key2 = "part"+i;
localStorage.setItem(key2,word[i]);
localWord.push(key2);
}
localStorage.setItem("localWord",JSON.stringify(localWord));
text2Array();
reveal();
}
return {
setLocalArray:setLocalArray
} ;
}());
and the from the outside you have to simply call arrayManager.setLocalArray()

access arrays of arrays or objects [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I would like to have an array of arrays like the following function shows.
function getarrayinfo(index)
{
var myarray1=new Array();
myarray[0]=[1,1.1,1.2];
myarray[1]=[0.1,0.2,0.3];
var myarray2=new Array();
for (myarray2[i])
{
myarray2[i]=myarray[i];
i++;
}
so I can do something like...
{
var arrayinfo=myarray2[marray1[index]];
return arrayinfo;
}
but this type of code does not seem to run..
Why will it run where there are Syntax errors in your code...
for (myarray2[i])
This is not how a for loop is written. Also you seem to access the index with i which is never initialized.
ALso
var myarray1=new Array();
myarray[0]=[1,1.1,1.2];
Created an myarray1 and trying to insert into myarray
Better to initialize an array with [] instead
Try this
for (var i=0; i< myarray1.length; i++) {
myarray2[i]=myarray[i];
}
Code
var myarray1 = []; // Use this to create an array
myarray1.push([1, 1.1, 1.2]); // Use push to instert instead of an index
myarray1.push([0.1, 0.2, 0.3]);
var myarray2 = [];
for (var i = 0; i < myarray1.length; i++) {
myarray2.push(myarray1[i]);
}
console.log(myarray2);
Check Fiddle
Step 1:Understand what is Multidimensional array (in your language--arrays of arrays)
var arr = [1, 2, [3, 4], 5];
alert (arr[2][1]); //alerts "4"
Step 2:this is what you want:
var container_array=[[a,b,c],[d,e,f]];
Step 3:Solution
var container_array=new Array();
sub_array_1=[1,1.1,1.2];
sub_array_2=[0.1,0.2,0.3];
container_array.push([1, 1.1, 1.2]);
container_array.push([0.1, 0.2, 0.3]);
console.log(container_array)
Example-->push in javascript
If you have many subarrays,then go for the loops

Add elements to 2D array in jquery [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to create a two dimensional array in JavaScript?
I want to push elements to 2D array,
My code is,
var results = [];
var resultstemp = [];
function bindlinks(aamt,id1) {
resultstemp=results;
imagesArray.push($("#image1").mapster("get"));
if(results.length==0)
{
results.push([id1]);
}
else
{
var ck=0;
var lng=results.length;
for (var i = 0; i < lng; i++) {
if(results[i]==id1)
{
ck=1;
results = jQuery.grep(results, function(value) {
return value != id1;
});
}
}
if(ck==0)
{
results.push(id1);
}
}
I want to push id as well as aamt to array. Here i am pushing only id to array. I am not sure about how to add aamt to second position in 2D array.
Help me please,
Thank you
Change the declaration as follows:
var results = new Array();
and change the push as follows:
results.push([id1,aamt]);
Hope it would help
The logic behind the method to push two separate values in the same array evenly is something like this:
var array = [];
function push(id1, aamt) {
for (var i= 0; i < 10; i++) {
if (i%2 == 0) {
array.push(id1);
}
else {
array.push(aamt);
}
}
}
push(10, 12);
console.log(array); // 10, 12, 10, 12.....
Take note i abstracted the code quite a bit, because for me was not too obvious what the code should have to do, but the principle is simple: use the modulo (%) operator to test if the value is odd or even. If odd add the first value if even add the second value.
Hope it helps.

Categories