I am trying to use the filter function to build a new array that provides only string values that are less than 10 in length. The function is however producing undefined values.
let move = (strings) => {
console.log('I got here');
let special = strings.length < 10;
if (special) {
console.log(strings);
return strings;
}
console.log(strings);
};
const username = [];
const validUserNames = (username) => {
username.filter(move);
};
//The code is expected to be called like this
//validUserNames(["Paul", "Barnabas", "Timothy", "Judas Iscariot"])
//Expected results: Paul, Barnabas, Timothy
In the move function, you need to return a boolean. Change it as follows :
let move = (string) => {
console.log('I got here');
let special = string.length < 10;
if (special) {
console.log(string);
return special;
}
console.log(string);
};
I have changed a few other things.
The function takes a single value in as filter goes through the array, so I changed strings to string.
Technically, it could be reduced to this.
let move = (string) => {
return string.length < 10;
};
I think there is also something else you aren't understanding. Having this code doesn't do anything.
const validUserNames = (usernames) => {
usernames.filter(move);
}
validUserNames(["Paul", "Barnabas", "Timothy", "Judas Iscariot"]);
Firstly, usernames.filter doesn't do anything to the usernames array, it returns the result of the filter.
Secondly, because you are not returning this result of the filter, validUserNames doesn't return anything.
Thirdly, unless you store the result of validUserNames in a variable, nothing will change in the state of the application.
I suggest you change the above to this.
const validUserNames = usernames.filter(move);
validUserNames will then store the array of strings with a length less than 10.
This is the correct solution. This function will take in any array of strings and will return string values that are lesser than 10 in length.
let move = (strings)=>{
console.log('I got here');
let special = strings.length < 10;
if(special){
console.log(strings);
return strings;
}
};
const username = [];
const validUserNames = (username)=>{let next = username.filter(move);
return next;
};
Related
I have this array
(2) ['beginning=beginner', 'leaves=leave']
and this string
its beginner in the sounds leave
which i have converted to an array
var words = text.split(' ');
i want to replace beginner with beginning and leave with leaves it can be any dynamic words but for now it has only two elements i can replace it within for loop. Is it possible with map method.
this.words.map((words, i) => console.log(words));
Note: Only first instance should get replaced.
Any Solution Thanks
does this correct with your question ?
const arrString = ["beginning=beginner", "leaves=leave", "sound=sounds"];
let string = "its beginner in the sounds leave";
arrString.forEach((mapString) => {
const stringArr = mapString.split("=");
string = string.replace(stringArr[1], stringArr[0]);
});
console.log("string", string);
// "its beginning in the sound leaves"
You can do it in without a nested loop too if you compromise with space.
Here is a solution which creates a mapping object for replacement values and uses array methods like map(),forEach(),join() and string method like split()
const arrString = ["beginning=beginner", "leaves=leave", "sound=sounds"];
let string1 = "its beginner in the sounds leave beginner";
const replaceObj = {};
const arrBreaks = arrString.forEach(x => {
let els = x.split("=");
replaceObj[els[1]] = els[0]; });
const ans = string1.split(' ').map((x) => {
if(x in replaceObj) { let val = replaceObj[x]; delete val; return val; }
return x;
}).join(' ');
console.log(ans);
I'm working on a problem where I'm mapping through arrays returned from an API call to create an array of graph point objects, however the data returned is unreliable and contains null values. In order to simplify the question, here's a short version of what I have now:
const APITimestamps = ['123','124','125','126','127','128']
const APIPrices = ['22.34','22,45',NULL,NULL,'22.89','22.32']
const chartData = APITimestamps.map((timestamp, index) => {
let graphPoint = {}
graphPoint.timestamp = APITimestamps[index]
graphPoint.price = APIPrices[index]
return graphPoint
}
The map works as is, however I need to rid the chartData of the null values where the API does not have a price some of the timestamps. What I would like to do is backtrack through the indexes of APIPrices being mapped until a non-null value is found, which in the above case would be ['22.34','22,45','22,45','22,45','22.89','22.32']. Any pointers on how to achieve this?
You can use a for loop that iterates backwards from the current index and finds the first non-null value.
const APITimestamps = ['123','124','125','126','127','128']
const APIPrices = ['22.34','22,45',null,null,'22.89','22.32']
const chartData = APITimestamps.map((timestamp, index) => {
let graphPoint = {}
graphPoint.timestamp = APITimestamps[index]
for(let i = index; i >= 0; i--){
if(APIPrices[i] !== null){
graphPoint.price = APIPrices[i];
break;
}
}
return graphPoint
});
console.log(chartData);
So i'm trying to build a function that can simplify expressions but I can't seem to find a way to seperate the terms into 2 different arrays (numbers and letters). The result of the code below is "32xy" instead of just "32".
Also it would be great to know if there is a better way to check for a number or selection of characters in javascript.
var newArr;
var numArr = [];
var letArr = [];
function splitTerm (term) {
for (var i=0; i<term.length; i++){
newArr = term.split('');
}
for (var item of newArr){
if (item === '0'|'1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9') {
numArr.push(item);
} else {
letArr.push(item);
}
}
$('#num').html(numArr.join(''));
}
splitTerm("32xy");
if (item === '0'|'1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9')
This should be
if (['0','1','2','3','4','5','6','7','8','9'].includes(item)) {
Also, you do'nt need to do that loop at the top of the function.
newArr = term.split(''); is fine to just run once.
Your code can be improved in many ways:
newArr, numArr, and letArr are only used inside the function, so you should declare them inside the function.
The for loop iterating from 0 to term.length does nothing except repeatedly assign the same thing to newArr, so it doesn't need to be there.
You can use a regex to test if something is a number.
function splitTerm(term) {
var newArr = term.split("");
for (var item of newArr) {
if (/\d/.test(item)) {
newArr.push(item);
} else {
letArr.push(item);
}
}
$("#num").html(numArr.join(""));
}
Another option - use regex
const splitTerm = (str) => {
// Use regexp to extract characters and digits
return {
dig: str.match(/\d+/g).join(''),
char: str.match(/[^\d]+/g).join(''),
};
};
// Run
const res = splitTerm("32xy");
// Log
console.log(res);
Here is the edited version
var newArr;
var numArr = [];
var letArr = [];
function splitTerm (term) {
numArr = Array.from(term).filter((elem) => /^[0-9]$/i.test(elem));
console.log(numArr.join(''));
}
splitTerm("322xy");
but you can actually use the value directly without function call;
$('#num').html(Array.from('32xy').filter((elem) => /^[0-9]$/i.test(elem)).join(''));
You can use .replace() with regular expression in your function.
console.log("32xy".replace(/[^0-9]/g, '')); // 32
console.log("aaa32xy".replace(/[^0-9]/g, '')); // 32
console.log("aaa3bb2xy".replace(/[^0-9]/g, '')); // 32
function countUniqueItems(arr) {
nums = [];
for (i = 0; i < arguments.length; i++) {
const item = arr[i];
console.log(i);
//console.log(item);
if (nums.includes(arr) === true) {
//console.log('8 is in the array');
//nums.push(arr)
} else {
nums.push(arr);
//console.log('8 is NOT in the array');
//nums.push(item)
}
}
return nums;
}
countUniqueItems(1, 2);
So it will give back the first argument which is 1 but i want it to be able to say argument 2 and 3 and so on
So you need to pass an array into the function, in place of 1,2 pass [1,2].
Then inside your function, you should use arr.length in place of arguments.length.
Then you look at your logic for the loop, you are pushing atm arr into nums, but if you pass and array that isn't really want you want, you should be pushing item as that is the variable which represents your current element from the array.
It looks from you comments like you're trying to make a unique list of inputs. Perhaps something like this would do the trick.
EDIT: Updated to use arguments
function uniqueNumbers() {
let arrayOfArguments = [...arguments]
let uniqueNums = [];
arrayOfArguments.map(i => !uniqueNums.includes(i) ? uniqueNums.push(i) : null);
return uniqueNums;
};
console.log(uniqueNumbers(1,2,3,3));
you should either pass an array to countUniqueItems or use the arguments keyword in the for-loop.
Your code is only seeing 1 (as arr inside the function).
basic implementation to find unique items
function countUniqueItems(...arr) {
let nums = [];
for (let num of arr) {
if (nums.indexOf(num) === -1) nums.push(num);
}
return nums;
}
console.log(countUniqueItems(1, 2, 1));
Using Set you can remove the duplicate values, you dont need to do logic run the loop to find the unique values from array.
const a = [1,2,3,3];
const uniqueSet = new Set(a);
uniqueSet.size
let uniqueFinder = arr => { const uniqueSet = new Set(arr); return uniqueSet.size}
const arrywithduplicates = [1,2,3,3,4,4];
uniqueFinder(arrywithduplicates) // return 4
Read more about Set : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
I'm very new in JavaScript and dont understand very well the definitions needed to a function work.
var ShowWords = ['Olá,','sabia','que', 'ta', 'tudo', 'bem?']
for(var i=0; i<ShowWords.length; i++){
console.log(ShowWords[i]);
}
And i dont get it why the code above works and the below doesn't, it only gives me "undefined"
function ShowWords(pal1,pal2,pal3,pal4,pal5,pal6){
for(var i=0; i<ShowWords.length; i++){
return ShowWords[i]
}
}
console.log(ShowWords['Olá,','sabia','que', 'ta', 'tudo', 'bem?']);
Anyone can help?
You have the wrong syntax for your function invocation. It needs to be function(args), not function[args].
This will work:
function ShowWords(words){
for(var i=0; i< words.length; i++){
return ShowWords[i]
}
}
console.log(ShowWords('Olá,','sabia','que', 'ta', 'tudo', 'bem?'));
But what you want to do, probably, is this:
function ShowWords(words){
for(var i=0; i< words.length; i++){
return ShowWords[i]
}
}
console.log(ShowWords(['Olá,','sabia','que', 'ta', 'tudo', 'bem?']));
But you really want to do this:
function ShowWords(words){
words.forEach(console.log)
}
ShowWords(['Olá,','sabia','que', 'ta', 'tudo', 'bem?']);
or this:
function makeListFromArray(words) {
return words.join(', ')
}
const list = makeListFromArray(['Olá,','sabia','que', 'ta', 'tudo', 'bem?']);
console.log(list);
Then you want to deal with the case where there is nothing passed in, or a string got passed in, and not throw an error:
function makeListFromArray(words = []) {
return Array.isArray(words) ? words.join(', ') : words;
}
const list = makeListFromArray(['Olá,','sabia','que', 'ta', 'tudo', 'bem?']);
console.log(list);
const str = 'Olá'
console.log(makeListFromArray(str)) // prints Olá
And then you can go leet and make it like this:
const makeListFromArray = (words = []) =>
Array.isArray(words) ? words.join(', ') : words;
const list = makeListFromArray(['Olá,','sabia','que', 'ta', 'tudo', 'bem?']);
console.log(list);
Those are a few ways to accomplish it. Don't use loops, array methods are more powerful, and composable.
And then, there was TypeScript...
const makeListFromArray = (words: string[] = []) => words.join(', ')
const list = makeListFromArray(['Olá,','sabia','que', 'ta', 'tudo', 'bem?']);
console.log(list);
With that single type annotation on (words: string[] = []), TypeScript will now refuse to build code that tries to pass anything other than an array of strings (or an empty array) to makeListFromArray.
It also knows that list is a string, because it knows that Array.join returns a string.
Since they are all const it knows that the value and type of list cannot change anywhere in the code, so it knows that list is a string everywhere.
First of all, use parens instead of brackets to call your function.
If you want to iterate all your arguments, you should use the spread operator (...) to gather all of them in an array, like this:
function ShowWords(...args) {
for (let i = 0; i < args.length; i++){
console.log(args[i]);
}
}
also, var is usualy kind of deprecated in JavaScript, I suggest you to use the let keyword instead.
If you only want to join all your arguments into a string, the join method seems to be the simpliest way:
function ShowWords(...args){
return args.join(" ");
}
console.log(ShowWords('Olá', 'sabia','que', 'ta', 'tudo', 'bem?'));
But if all you need is to display words in the console, you must put the console.log function directly inside your loop and don’t use return which breaks the loop and exits the function. for ... of loops or forEach array method are a good way to do that:
function ShowWords(...args){
args.forEach(word => console.log(word));
}
ShowWords('Olá', 'sabia','que', 'ta', 'tudo', 'bem?');
function ShowWords(...args){
for (const word of args) {
console.log(word);
}
}
ShowWords('Olá', 'sabia','que', 'ta', 'tudo', 'bem?');
You have multiple solution to do this. Others answers just give you the basic old way to do it with an array and a for loop (and this is valid!) but I want to give you others solutions:
Using One string/args and use spread operator to keep then all:
const convertToStr = (...args) => {
// args is an array containing all args.
};
Usage:
convertToStr("My", "First", "String");
Or
const words = ["My", "first", "string"];
convertToStr(...words); // << Deconstruct the array to give one element / args
Note that both solution give you the exact same result.
The content of the function:
If you have an array of string and want to concat them together you should use Array.join()
const convertToStr = (...args) => {
const allStrings = args.join(" "); // < Space with " ", put "" for nothing,
console.log(allStrings);
}
The second code does not work for multiple reasons. First use unique name for function and variable. Secondly if you are passing an array , the function is expected to accept sing argument only. Thirdly you are returning from the for statement , the function will return after processing first element
var ShowWords = ['Olá,', 'sabia', 'que', 'ta', 'tudo', 'bem?']
function convertToStr(arr) {
let str = '';
for (var i = 0; i < arr.length; i++) {
str += arr[i] + ' ';
}
return str.trim();
}
console.log(convertToStr(ShowWords))