how to compare 2 digits number in array - javascript

I am writing a program to find duplictate number in array. The following program is working when number are single digits but for double digit number it is not working
var containsDuplicate = function(nums) {
num = nums.sort()
if (num.length === 0) {
return false
} else {
for (let i = 0; i < num.length; i++) {
if (num[i] == num[i + 1]) {
return true;
} else {
return false
}
}
}
}

First update your condition to num.length-1 to not run out of boundaries. Second return true if there is a duplicate but don't return false inside the else block.
When no duplicate was found then return false at the end of the function.
function containsDuplicate(nums) {
num = nums.sort()
if (num.length === 0) {
return false
} else {
for (let i = 0; i < num.length-1; i++) {
if (num[i] === num[i + 1]) {
return true;
}
}
}
return false;
}
console.log(containsDuplicate([2,3,4,4,5]))

If you want to remove duplicates, you can proceed in the following way:
let a = (x) => {return Array.from(new Set(x))};
a([1,2,3,4,5,6,7,8,9,10,11,12,11,11,9,8,10,11,12]);
Expected output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
Hope that it is what you wanted.

Related

How do I use if statement to return -1 if what I am searching for is not in my array?

I need to return the index place of my target and if my target is not present in my nums array I need to return -1. When I run my code it is like only my second return works?
function search(nums, target) {
for (let i = 0; i < nums.length; i++) {
let exist = nums[i]
if (exist == target) {
return [nums.indexOf(exist)]
} else {
return -1
}
}
}
console.log(search([-1, 0, 3, 5, 9, 12], 9))
You need to move the return -1 statement outside of the for loop
try this
function search(nums, target) {
for (let i = 0; i < nums.length; i++) {
let exist = nums[i];
if (exist == target) {
return i;
}
}
return -1;
}
console.log(search([-1, 0, 3, 5, 9, 12], 9));

How can I return the mode that appeared first in an array in Javascript?

I want to create a function that will return the number with highest frequency(mode). For example: if array contains [10, 4, 5, 2, 4] the output should be 4. If there is more than one mode, I want to return the one that appeared in the array first (ie. [10,2,5, 4, 5, 2, 4] should return 2 because it appeared first. If there is no mode, I want to return -1. The array will not be empty. Below is my attempt
function Mode(arr){
if(arr == undefined || arr.length == 0){
return
}
const number_to_frequency = {};
let number_with_overall_highest_frequency = 0;
let overall_highest_frequency = 0;
for(index in arr) {
const number = arr[index];
if(number_to_frequency[number]) {
number_to_frequency[number] += 1;
} else {
number_to_frequency[number] = 1;
}
let updated_frequency = number_to_frequency[number]
if(overall_highest_frequency < updated_frequency) {
number_with_overall_highest_frequency = number;
overall_highest_frequency = updated_frequency;
}
}
if(overall_highest_frequency == 1){
return -1
}
return number_with_overall_highest_frequency;
};
console.log(Mode([10,2,5, 4, 5, 2, 4])) //5
If you only need the first one that its repeated you can try this approach
const checkMode = (array = []) => {
const duplicated = array.find(value => array.filter(_value => value === _value).length > 1)
return duplicated >= 0 ? duplicated: -1
}
checkMode([10,2,5, 4, 5, 2, 4])

Tallying in nested arrays and returning the object

Looking for some help with a problem as I'm very new to Javascript.
I want to write a function that tallies up feedback scores as shown in the code below. I want to take an array with nested arrays and if the score given is below 3 it should increase the negative property, if it's in the range 4 - 6 the neutral property should increase and when it's in the 7 - 10 range, it's positive that should increase.
I continue to simply receive in the console log
{positive: 0, negative: 0, neutral: 0}
which obviously isn't the expected output. What is wrong?
function gatherFeedback(feedbackArray) {
let result = {
positive: 0,
negative: 0,
neutral: 0
};
if (feedbackArray > 0) {
for (let i = 0; i < feedbackArray; i++) {
if (feedbackArray[i][1] >= 7) {
result.positive++
} else if (feedbackArray[i][1] <= 3) {
result.negative++
} else if (feedbackArray[i][1] > 3 && feedbackArray < 7) {
result.neutral++
}
}
}
return result;
}
console.log(gatherFeedback([
['feedback1', 10],
['feedback2', 3],
['feedback3', 6]
]))
Your main issue is with this line:
if(feedbackArray > 0){
When you try to compare an array to an integer the array first gets converted into a string, which in this case yields:
"feedback1,10,feedback2,3,feedback3,6"
comparing this to 0 yields false (see the description here as to why) so your loop never runs. The same problem will apply with the next line where you have:
i < feedbackArray
It's simpler just to use a for...of loop (note you can also simplify your if/else structure):
function gatherFeedback(feedbackArray) {
let result = {
positive: 0,
negative: 0,
neutral: 0
};
for (let f of feedbackArray) {
if (f[1] >= 7) {
result.positive++
} else if (f[1] > 3) {
result.neutral++
} else {
result.negative++
}
}
return result;
}
console.log(gatherFeedback([
['feedback1', 10],
['feedback2', 3],
['feedback3', 6]
]))
Change your code to this
function gatherFeedback (feedbackArray) {
let result = {positive: 0, negative: 0, neutral: 0};
if(feedbackArray.length > 0){
for(let i = 0; i < feedbackArray.length; i++) {
if(feedbackArray[i][1] >= 7) {
result.positive++
} else if(feedbackArray[i][1] <= 3){
result.negative++
} else if (feedbackArray[i][1] > 3 && feedbackArray[i][1] < 7) {
result.neutral++
}
}
}
return result;
}
Use .length array property:
function gatherFeedback(feedbackArray) {
let result = {
positive: 0,
negative: 0,
neutral: 0
};
if (feedbackArray.length > 0) {
for (let i = 0; i < feedbackArray.length; i++) {
if (feedbackArray[i][1] >= 7) {
result.positive++
} else if (feedbackArray[i][1] <= 3) {
result.negative++
} else if (feedbackArray[i][1] > 3 && feedbackArray < 7) {
result.neutral++
}
}
}
return result;
}
console.log(gatherFeedback([
['feedback1', 10],
['feedback2', 3],
['feedback3', 6]
]))

Checking if array is growing and print the missing element

var growing = function (array) {
for (var i = 0; i < array.length; i++) {
if (array[i] > array[i + 1]) {
return false;
} else {
return true;
}
}
function missing(array) {
for (var i = 0; i < array.length - 1; i++) {
if (array[i + 1] !== array[i] + 1) {
return array[i] + 1;
}
}
}
};
I got two tasks assigned and I need your help. Firstly in the 'growing' function I have to check if array is growing. For example, for array [1,2,3,4,5,6,7] it should return true but for [1,2,10,4,5,6,7] false. I am completely out of ideas for this loop, how can I upgrade my loop? Secondly, in the 'missing' function, I have to iterate through whole array and check if it's iterating, I mean if array is like this: [1, 2, 3, 5,] it shall return 4, if array is iterating fine without "jumps" it shall return null. When I am trying to add 'else' loop with condition return null; it's just breaking my whole loop and it's returning null for every array. What's wrong?
Yow was almost there, see comments in code:
var growing = function (array) {
for (var i = 0; i < array.length; i++) {
if (array[i] > array[i + 1]) {
return false; // return only when it is not growing
}
}
// if not returned in loop, then array is ascending
return true;
};
// define function outside of growing function
function missing(array) {
for (var i = 0; i < array.length - 1; i++) {
if (array[i + 1] !== array[i] + 1) {
return array[i] + 1;
}
}
}
console.log(growing([1,2,3,4,5,6,7])); // true
console.log(growing([1,2,10,4,5,6,7])); // false
console.log(missing([1,2,3,4,5,6,7])); // undefined
console.log(missing([1, 2, 3, 5,])); // 4
For the first part, I suggest to use Array#every()
function isGrowing(array) {
return array.every(function (a, i, aa) {
return !i || aa[i - 1] + 1 === a;
});
}
document.write(isGrowing([1, 2, 3, 4, 5, 6, 7]) + '<br>');
document.write(isGrowing([1, 2, 10, 4, 5, 6, 7]) + '<br>');
document.write(isGrowing([1, 2, 3, 5, ]) + '<br>');

How to calculate certain chars from a string

i'm looking for this since yesterday, already searched a lot but didn't find any answer for exactly what I need. If you find any, just tell me, i'll appreciate and close this question :)
What I want is:
-> If there are an even number of digits, double every other digit starting with the first
-> If there are an odd number of digits, double every other digit starting with the second.
This is what I did so far:
function validate(n){
var num = n.toString(); // THIS COULD BE AN ARRAY OR WHATEVER
if (eval(num%2==0)) { // IF HAS EVEN NUMBER OF DIGITS
for (var i=0; i<num.length; i++) {
if (num.charAt(i) === num.charAt(0)) {
eval(num.charAt(i)*=2);
}
}
console.log(num);
} else { // IF HAS ODD NUMBER OF DIGITS
for (var i=0; i<num.length; i++) {
if (num.charAt(i) === num.charAt(1)) {
eval(num.charAt(i)*=2);
}
}
console.log(num);
}
}
validate(1234516178);
Examples:
1714 => [1*, 7, 1*, 4] => [2, 7, 2, 4]
891 => [8, 9*, 1] => [8, 18, 1]
Hope I was clear. Can someone help on this? Appreciate!
Maybe this works for you. It utilizes an array with the values and iterates over the values to change.
function validate(n) {
var array = n.toString().split('').map(Number),
number = n % 2 ? array[1] : array[0];
return array.map(function (a) {
return a === number ? 2 * a : a;
});
}
function print(o) {
document.write('<pre>' + JSON.stringify(o, 0, 4) + '</pre>');
}
print(validate(1234516178));
print(validate(1714)); // => [1*, 7, 1*, 4] => [2, 7, 2, 4]
print(validate(891)); // => [8, 9*, 1] => [8, 18, 1]
You could try something like this:
function validate(n) {
n = n.toString();
var isEven = (parseInt(n, 10) % 2 === 0);
var digits = n.split("");
// Strings to numbers
digits.forEach(function(digit, index) {
digits[index] = parseInt(digit, 10);
});
if(isEven) {
var firstDigit = digits[0];
digits.forEach(function(digit, index) {
console.log(digit);
if(digit === firstDigit) {
digits[index] *= 2;
}
});
} else {
var secondDigit = digits[1];
digits.forEach(function(digit, index) {
if(digit === secondDigit) {
digits[index] *= 2;
}
});
}
return JSON.stringify(digits);
}
This can be of course be made better with including more conditions and leaving just a single forEach
You dont need strings to do that
function validate(s){
var a = parseInt(s);
var b = 0;
var odd = (a+'').length %2//true;
//var summ = 0;
while(a>=1){
var b = Math.floor(a%10);
var c = odd?b: b*2//<10? b*2 : b*2-9;
//summ += c;
odd = !odd;
a = a/10;
//output
$('input').after('+'+c)
}
//output
$('input').after('<br>')//.after(summ).after('<br> summ: ')
//return summ%10
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="validate($('input').val())">validate</button>
<input>

Categories