checking multiple elements in javascript array - javascript

I have an array 'type' with multiple elements.how to check two elements contains in 'type' array?
i have tried the below code
var i, j;
var type = [];
for (i = 1; i <= count; i++)
{
var filetype_value = parseInt((document.submission['select_type_' + i].value));
type.push(filetype_value);
}
function search(arg)
{
for (j = 1; j <= count; j++)
{
if (type[j] === arg)
{
return true;
}
else
{
return false;
}
}
}
if(search(1) && search(2))
{
alert("Contains in array")
}

There is some problems with your approach.
1) You are just checking if type[1]===arg it will return true otherwise it will return false. So it will just check for type[1].
2) because file_type value is string so filetype_value' === arg is never going to be true.
3) In your loop j=1 will never check for first element of array.
Try this
function search(arg){
var matched = false;
for (j = 0; j <= type.length; j++){
if (type[j] == arg){
matched = true;
break;
}
}
return matched;
}

You have 2 problems
You are pushing the string "filetype_value" onto your array and not the actual value so in your search function you are actually testing: 'filetype_value' === arg
You are starting your loop using 1, array's start at an index of 0
change
type.push('filetype_value');
to
type.push(filetype_value);
change
for (j = 1; j <= count; j++)
to
for (j = 0; j <= count; j++)
Also instead of doing a loop you can use the array indexOf method to test if a value is in the array
function search(arg){
return type.indexOf(arg) !== -1;
}

Related

naive string matching algorithm gone wrong

I am trying to implement naive search and I do not get the expected result. Can anyone point out here, what could be the possible error.
function naive(string, str) {
for (let i = 0; i <= string.length - str.length; i++) {
if (string[i] == str[0]) {
let counter = 1
for (let j = 1; j <= str.length; j++) {
if (string[i + j] == str[j]) {
counter++;
console.log(counter)
} else
counter = 0;
}
if (counter == str.length) {
console.log(`${counter} pattern matched at ${i}`)
}
} else
console.log('nothing matched')
}
}
var match_found = false;
function naive(string, str){
for(let i =0; i <= string.length - str.length; i++){
if(string[i] == str[0]){
let counter= 1
for(let j = 1; j < str.length; j++){
if(string[i + j] == str[j]){
counter++;
}else{
break;
}
}
if(counter == str.length){
console.log('Pattern matched at ' + i);
match_found = true;// can break; here if you wish to, else it will give you all matches present
}
}
}
if(match_found === false){
console.log(str + ' not found in ' + string);
}
}
naive('abcdgggabcdggg','ggg');
You increment the counter when there is a match, but you need to break the loop where there is a mismatch.
Your inner for loop condition needs to have j < str.length instead of j <= str.length, because index starts from 0.
else console.log('nothing matched'). You can't just instantly decide that. If a string index doesn't match, you need to still keep looking for the rest of the indexes.
Best way to go about it is to maintain a boolean flag for it as shown in the above code.
You don't need to do all that iteration and comparison by yourself. Here's a simpler version of your function:
function naive(string, str) {
var counter = 0,
i = string.indexOf(str, 0); //find first occurance of str in string
while(i !== -1){
++counter; //we have a match, count one up
console.log(`counter %i, index %i`, counter, i);
i = string.indexOf(str, i+1); //find next occurance
}
return counter;
}
console.log("result", naive("lorem upsum", "m"));

this code is supposed to delete duplicate values and delete empty spaces but it is deleting unique values as well

this code is supposed to delete duplicate values and delete empty spaces but it is deleting unique values as well.
cnt = 0;
for (let i = 0; i < this.fin.length; i++) {
for (let j = 0; j < this.fin.length; j++) {
if (this.fin[i] == this.fin[j]) {
cnt++;
if (cnt > 1) {
this.fin[j] = '';
}
}
if (j == this.fin.length - 1) {
cnt = 0;
}
}
}
this.ntmtg1 = true;
count = 0;
for (let j in this.fin) {
if (this.fin[j] == '') {
this.fin.splice(parseInt(j));
}
}
your logic is almost correct. The couple of mistakes you did are:-
In the for loop in the last part of your code, when you use for( let i in SomeCollection) 'i' will be the value and not index in the array. I think you want to access the index and not the value. I think you should use should use traditional for loop like for(int i =0; i<fin.length;i++).
You need to use splice with two arguments to delete some value from the array.
here is the link https://www.w3schools.com/jsref/jsref_splice.asp
You can do that in simply just one line of code with ES6 feature and Set :
var fin = ["Vivek","Vivek","Mak","Nik","Mak","Hir","Hari","Nur","Nik"];
var result = [...new Set(fin)];
console.log("Fin Total :" , fin.length , ", Result Total :" , result.length);
console.log(result);
Couple of fixes to your code
don't use for in if you're going to mutate the array
splice with only one argument splices from the index to the end of the array, so add a second argument, the length of the splice
in the code below, I omit this for simplicity
Also, I moved were cnt is defined, so no if condition gymnastics needed to reset it
const fin = [1,3,6,7,3,2,4,5,6,4,3,2,1,4,5];
for (let i = 0; i < fin.length; i++) {
let cnt = 0;
for (let j = 0; j < fin.length; j++) {
if (fin[i] == fin[j]) {
cnt++;
if (cnt > 1) {
fin[j] = '';
}
}
}
}
let count = 0;
for (let i = 0; i < fin.length; i++) {
if (fin[i] == '') {
fin.splice(i, 1);
--i; // we've removed an item
}
}
console.log(fin);
fin:any = ["OMAD","SVAC","SVCH","SVAD","LGAG","OMAM","OTBK","OTBH","LGAX","LGBL","SVAN","LGAD","SVAB","SKAP","LGRX","SVAA","SVAS","DNAS","EGEI","NCAT","SVBS","SVBL","SVFM","EPKG","OBBB","OBBS","OBKH","LTFD"
,"SVBC","SVBI","SVBM","SVBB","SVBO","TNCB","SVBZ","SKBU","SKBN","SVCI","SVCD","SVCL","SVCN","SVCC","SVCS","SVCO","SVCZ","SKGO","SVCP","NZCG","SVQM","SVCA","LGSA","MWCB","CYCK","SVCB","SVPI","MRCU","EKCN"
,"SVCR","SKCV","SVUR","SVCU","SVRB","TNCF","TNCC","LGTT","VRMD","OMDW","SVLL","SVED","SVRS","SVEM","SVJI","SVVG","LGEL","SVEZ","NZEV","EDTF","SVFT","VRMR","SKGB","SVGU","SVGD","SVGT","SVGI","SVQJ","EKHM"
,"SVQF","LSPK","SVQL"];

why does it returns '-1' instead of the index of the index jQuery

I'm running a 'for' loop to check if the elements in the winOptions array are in the oneNums array. However, every time I use indexOf property it sends back -1 even if the number is in the oneNums array. Is it possible it returns that because ['1','2'] is different that [1,2]? How can I fix this.
I have this variables:
var oneNums = [];
var winOptions = [[1,2,3],[4,5,6],[7,8,9],[1,5,9],[3,5,9],[1,4,7],[2,5,8],[3,6,9]];
var a;
And this jQuery function:
$('.btn-xo').click(function(){
if (turn === 'one'){
$(this).text(pickOne);
$(this).prop('disabled', true);
oneNums.push($(this).val());
oneNums.sort(function(a, b){
return a - b;
});
for(var i = 0; i < winOptions.length; i++){
for(var j = 0; j < winOptions[i].length; j++){
a = oneNums.indexOf(winOptions[i][j]);
if (a === -1){
p1 = [];
break;
} else {
p1.push(oneNums[a]);
console.log('aca');
}
}
}
console.log(a);
turn = 'two';
count += 1;
}
indexOf string with number will fail. So, change number to string
First convert number to String, using .toString()
for(var i = 0; i < winOptions.length; i++){
for(var j = 0; j < winOptions[i].length; j++){
a = oneNums.indexOf((winOptions[i][j]).toString());
if (a === -1){
p1 = [];
break;
} else {
p1.push(oneNums[a]);
console.log('aca');
}
}
}
Check these two examples,
['1','2'].indexOf(1); o/p ===> -1
['1','2'].indexOf((1).toString()); o/p ===> 0

Searching a 2D Javascript Array For Value Index

I am trying to write a jQuery that will find the index of a specific value within a 7x7 2D array.
So if the value I am looking for is 0 then I need the function to search the 2D array and once it finds 0 it stores the index of the two indexes.
This is what I have so far, but it returns "0 0" (the initial values set to the variable.
Here is a jsFiddle and the function I have so far:
http://jsfiddle.net/31pj8ydz/1/
$(document).ready( function() {
var items = [[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,0,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7]];
var row = 0;
var line = 0;
for (i = 0; i < 7; ++i) {
for (j = 0; i < 7; ++i) {
if (items[i, j] == '0,') {
row = i;
line = j;
}
}
}
$('.text').text(row + ' ' + line);
});
HTML:
<p class="text"></p>
Your if statement is comparing
if (items[i, j] == '0,')
Accessing is wrong, you should use [i][j].
And your array has values:
[1,2,3,4,5,6,7]
....
Your value '0,' is a string, which will not match numeric values inside the array, meaning that your row and line won't change.
First, you are accessing your array wrong. To access a 2D array, you use the format items[i][j].
Second, your array doesn't contain the value '0'. It doesn't contain any strings. So the row and line variables are never changed.
You should change your if statement to look like this:
if(items[i][j] == 0) {
Notice it is searching for the number 0, not the string '0'.
You access your array with the wrong way. Please just try this one:
items[i][j]
When we have a multidimensional array we access the an element of the array, using array[firstDimensionIndex][secondDimensionIndex]...[nthDimensionIndex].
That being said, you should change the condition in your if statement:
if( items[i][j] === 0 )
Please notice that I have removed the , you had after 0. It isn't needed. Also I have removed the ''. We don't need them also.
There are following problems in the code
1) items[i,j] should be items[i][j].
2) You are comparing it with '0,' it should be 0 or '0', if you are not concerned about type.
3) In your inner for loop you should be incrementing j and testing j as exit condition.
Change your for loop like bellow and it will work
for (i = 0; i < 7; i++) {
for (j = 0; j < 7; j++) {
if (items[i][j] == '0') {
row = i;
line = j;
}
}
}
DEMO
Note:-
1) Better to use === at the place of ==, it checks for type also. As you see with 0=='0' gives true.
2) Better to say i < items.length and j<items[i].length instead of hard-coding it as 7.
var foo;
items.forEach(function(arr, i) {
arr.forEach(function(val, j) {
if (!val) { //0 coerces to false
foo = [i, j];
}
}
}
Here foo will be the last instance of 0 in the 2D array.
You are doing loop wrong
On place of
for (i = 0; i < 7; ++i) {
for (j = 0; i < 7; ++i) {
if (items[i, j] == '0,') {
row = i;
line = j;
}
}
}
use this
for (i = 0; i < 7; i++) {
for (j = 0; j < 7; j++) {
if (items[i][j] == 0) {
row = i;
line = j;
}
}
}
Here is the demo
looks like you are still learning how to program. But here is an algorithm I've made. Analyze it and compare to your code ;)
var itens = [[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,0,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7]];
var row = null;
var collumn = null;
for (var i = 0; i < itens.length; i++) {
for (var j = 0; j < itens[i].length; j++) {
if (itens[i][j] == 0) {
row = i;
collumn = j;
}
}
}
console.log(row, collumn);

Checking and deleting multiple occurrences of the same value in an array using javascript

This is what I've been trying, but something is wrong with the last part, can sy please tell me whats wrong, or show me an other method of doing this. Thanks in advance.
function removeSpaces(string) {
var str = string.replace(/^\s*|\s*$/g,'')
str = str.replace(/[^a-z|A-z|\r\n]/g,'');
while (str.indexOf("\r\n\r\n") >= 0) {
str = str.replace(/\r\n\r\n/g, "\r\n");
}
words = str.split("\r\n");
var i = 0;
var j = 0;
for (i = 0; i < words.length; i++) {
for (j = i; j < words.length; j++) {
if ((i != j) && (words[i] == words[j])) {
words.splice(j,1);
j--;
}
}
}
str = words.join("\r\n");
return str;
}
You could use the filter function. The filter function of an array is returning an array containing elements which pass to a certain filter.
var isLastElement = function(element, index, array){
return (index == array.lastIndexOf(element));
};
words = words.filter(isLastElement);
In this example, the filter function goes through the elements of the initial array ad add this element to the new array only if isLastElement(element, elementIndex, initArray) return true.
The isLastElement function returns true only if the element is not present a second time in the end of the array.

Categories