How do i display the longest array in JS? - javascript

I want to create a Javascript array of words, then use Javascript to find the longest word and print it to the screen. Here is my code:
var StrValues = []
StrValues[0] = ["cricket"]
StrValues[1] = ["basketball"]
StrValues[2] = ["hockey"]
StrValues[3] = ["swimming"]
StrValues[4] = ["soccer"]
StrValues[5] = ["tennis"]
document.writeln(StrValues);

You can use length to find the longest string in a array. Here is a fiddle http://jsfiddle.net/2sebnb33/1/
for(var i=0;i<StrValues .length;i++){
if(StrValues [i].length>len){
len=StrValues [i].length;index=i;}
}

var strValues = ["cricket", "basketball", "hockey"];
var max = '';
for(var i = 0; i< strValues.length; i++) {
max = strValues[i].length > max.length ? strValues[i] : max;
}
alert(max);

Firstly, you need to correct the way you are creating array.
For instance, it should be like this
var StrValues = [];
StrValues[0] = ["cricket"];
The logic
var longestWord = "";
for (var i = 0 ; i < StrValues.length; i++) {
if(StrValues[i].length > longestWord.length) {
longestWord = StrValues[i];
}
}

See the code below:
var array = [];
array.push("cat");
array.push("children");
array.push("house");
array.push("table");
array.push("amazing");
var maxSize = 0;
var maxSizeWord = "";
for(var i = 0; i < array.length; i++) {
if (maxSize < array[i].length) {
maxSize = array[i].length;
maxSizeWord = array[i];
}
}
alert("The biggest word is '" + maxSizeWord + "' with length '" + maxSize + "'!");

Related

how to replace same words in javascript multiple times?

Our developer used this phone number 1-866-579-469 all over the website but the correct phone number is 1-866-579-4269. I have written a javascript function to replace all occurrences:
var nodes,currentElement,oldtext,newtext,replaced,count;
function replaceAll(nodes,oldtext,newtext,replaced) {
count = 0
for (var i = 0; i < nodes.length; i++) {
currentElement = nodes[i].innerHTML;
replaced = currentElement.replace(oldtext,newtext);
count++;
}
console.log("Edited: "+ count + " items");
}
oldtext = "1-866-579-469";
newtext = "1-866-579-4269";
nodes = document.getElementsByTagName('*');
replaceAll(nodes,oldtext,newtext,replaced);
Your code works but you missed to update the replaced string. This should work:
var nodes,currentElement,oldtext,newtext,replaced,count;
function replaceAll(nodes,oldtext,newtext,replaced) {
count = 0
for (var i = 0; i < nodes.length; i++) {
currentElement = nodes[i].innerHTML;
replaced = currentElement.replace(oldtext,newtext);
nodes[i].innerHTML = replaced;
count++;
}
console.log("Edited: "+ count + " items");
}
oldtext = "1-866-579-469";
newtext = "1-866-579-4269";
nodes = document.getElementsByTagName('*');
replaceAll(nodes,oldtext,newtext,replaced);
Codepen Here

replace string using array in javascript

abc1 abc2 abc3
abc4 abc5 abc6
abc7 abc8 abc9
using above csv file, load text by replacing the double quotes from the bellow sentence.
Sentence:
"" is going with "" to "" for something to know.
Expected out put is:
abc1 is going with abc2 to abc3 for something to know.
abc3 is going with abc5 to abc6 for something to know.
like this in javascript, php.
Code I have tried so far:
var s = 'Neque porro "" estqui "" dolorem';
var insert = [["a1", "b1"]["c1","d1"]];
console.log(insert);
var words = new Array();
words = s.split(" ");
console.log(words);
var count = 0;
for (i = 0; i < words.length; i++) {
for (j = 0; j < insert.length; j++) {
if(words[i] == '""')
s = s.replace(/""/, insert[j]);
}
}
console.log(s);
Hurray I got the answer:
reader.onload = function (e) {
var sent = ''; var sentt = ''; var senttt = '';
sent = $('#mixmsg').val();
var quoteLength = (sent.match(/""/g) || []).length;
var rowcells = [];
rows = e.target.result.split("\n"); alert(rows);
for (var i = 0; i < rows.length; i++) {
var cells = rows[i].split(",");
rowcells.push(cells);
}
var rowcellso = rowcells.slice(0, -1);
console.log(rowcellso);
for (var ro = 0; ro < rowcellso.length; ro++) {
for (var scol = 0; scol < quoteLength; scol++) {
sent = sent.replace(/""/,rowcellso[ro][scol]);
console.log(rowcellso[ro][scol]);
} sentt +=sent+'\n'; sent= $('#mixmsg').val();
}
$('#container').html(sentt);
}

Javascript Can't use array content as array index?

When I trird to run the js code, it always said "Uncaught TypeError: Cannot read property '_id' of undefined" for
deployedID.push(data[j]._id);
So after some thinking, I believe the problem lies in
var j = deploy[i];
Is there any way to solve it? Thanks in advance.
Below is the complete code:
var deploy = [];
var deployedID = [];
var deployedename = [];
var deployedoname = [];
var deployedrank = [];
function popularizeTable(){
$.get("/SSS/getlist", function(data){
deploy = randomunique(data.length ,100);
for (var i = 0; i < 100; i++){
var j = deploy[i];
deployedID.push(data[j]._id);
deployedename.push(data[j].ename);
deployedoname.push(data[j].oname);
deployedrank.push(data[j].rank);
}
var str = " ";
var k = 0;
for (var i = 0; i < 5; i++){
str += "<tr>";
for(var j = 0; j < 20; j++){
str += "<td><section id=\"" + deployedID[k] + "\" class=\"container\"><div class=\"card\">"
str += "<figure class=\"front\"><img src=\"images/back.jpg\"></figure>";
str += "<figure class=\"back\"><img src=\"images/Clear/" + deployedename[k] + "/001.jpg\"></figure></div></td></section>";
k++;
}
str += "</tr>";
}
$("#table").append(str);
});
}
$( document ).ready(function() {
popularizeTable();
$(document).on("mouseover", ".card", function(){
$(this).toggleClass("flipped")});
});
function randomunique(max, num){
var uniquelist = [];
for (var j = uniquelist.length; j < num; j++){
var i = parseInt(Math.random() * (max - 1) + 1);
if (uniquelist.indexOf(i) == -1){
uniquelist.push(i);
}
}
return uniquelist;
}

finding and placing a word from the text in an array

I am trying to find a word in the text with my name. The code requires me to first find the first character of the word and then subsequently push the remaining letters in the hits[] array. I am trying but got stuck.
var text = "This is just Rohit.";
var myName = "Rohit";
var hits = [];
for (var i = 0; i < text.length; i++)
{
if(text[i] === myName[0] )
{
for(j = 0; j < myName.length; j++)
{
hits.push(text[i]);
};
};
};
hits;
var text = "This is just Rohit.";
var myName = "Rohit";
var hits = [];
for (var i = 0; i < text.length; i++) {
if(text[i] === myName[0] ) {
for(var j = i, l = 0; l < myName.length; j++, l++) {
hits.push(text[j]);
}
}
}
console.log(hits.join(''));
Just ignore the searchtext and go with the searchterm.
var hits = [];
var i=0;
while (i<"Rohit".length) arr.push("Rohit"[i++]);
console.log(hits);
// ["R", "o", "h", "i", "t"]
Something like this should help.Let me know if a change is needed.
var text = "This is just Rohit.";
var myName = "Rohit.";
var hits = [];
var array1=text.split(" ");
for (var i = 0; i < array1.length; i++)
{
if(array1[i]==myName)
{
hits.push(array1[i].split(''));
}
}
THIS PART IS THE METHOD WHICH YOU WERE USING::
var text = "This is just Rohit.";
var myName = "Rohit";
var hits = [];
var x='';
for (var i = 0; i < text.length; i++)
{
if(text[i] === myName.charAt(0) && text[i-1]==" " )
{
for(j = i; j < (i+myName.length); j++)
{
console.log(text[j]);
x=x+text[j];
}
}
}
hits[0]=x;
alert(hits);
After looking at your comments for clarification, it looks like you just want your name as the only element in a new array.
Use this:
var text = 'Your name is Rohit.';
var name = 'Rohit';
var hits = [text.substring(text.indexOf(name), text.indexOf(name) + name.length)];
console.log(hits);
// ["Rohit"]
Can't imagine how this is helpful, but the code above will do what you want.
I solved it.
var text = "This is just Rohit.";
var myName = "Rohit";
var hits = [];
for (var i = 0; i < text.length; i++)
{
if(text[i] === myName[0] )
{
for(var j = i; j < (myName.length+i); j++)
{
hits.push(text[j]);
};
};
};
hits;

making groups with random names in it in javascript

I am new to coding Javascript. I am trying to to shuffle list of names inputted on a textarea. The user selects the number of groups desired, and shuffle on click, then show the divided groups as output result. Below is my code but it is not working as it should be, pls help!
<script>
function ArrayToGroups(source, groups){
var groupList = [];
groupSize = Math.ceil(source.length/groups);
var queue = source;
for(var r = 0; r < groups; r++){
groupList.push(queue.splice(0,groupSize));
}
return groupList;
}
function textSpliter(splitText){
var textInput = document.getElementById("inputText").value;
var splitText = textInput.split(',');
var newList = [];
for(x = 0; x <= splitText.length; x++) {
var random = Math.floor(Math.random() * splitText.length);
var p = splitText[random];
newList.push(p);
splitText.splice(p,groupList);
}
for(var i = 0; i < newList.length; i++){
var s = newList[i];
document.getElementById('resInput').value += s + "\n" ;
}
return splitText;
}
</script>
Below is my input and output textareas
</head>
<body>
<form>
<textarea id="inputText" placeholder="text" rows="10" cols="40"></textarea>
<input type="number" name="number" max="6" value="1" id="groupNumber">
<textarea id="resInput" placeholder="text" rows="10" cols="40"></textarea>
<input type="button" name="Shuffle" value="shuffle" onclick="textSpliter()">
</form>
</body>
</html>
function shuffle() {
// Get list
// Example: element1, element 2, ele ment 3, ...
var list = document.getElementById("inputText").value.replace(/\s*,\s*/g, ",").split(",");
// Get number of groups
var n = parseInt(document.getElementById("groupNumber").value);
// Calculate number of elements per group
var m = Math.floor(list.length / n);
// Enought elements
if (n * m == list.length) {
// Create groups
var groups = new Array();
for (i = 0; i < n; i++) {
groups[i] = new Array();
for (j = 0; j < m; j++) {
// Random
rand = Math.floor(Math.random() * list.length);
// Add element to group
groups[i][j] = list[rand];
// Remove element to list
list.splice(rand, 1);
}
}
// Output
var text = "";
for (i = 0; i < n; i++) {
text += "Group " + (i + 1) + ": ";
for (j = 0; j < m; j++) {
if (j != 0) { text += ", "; }
text += groups[i][j];
}
text += "\n";
}
document.getElementById("resInput").value = text;
} else {
alert("Add more elements");
}
}
I rewrote your code. It's pretty self-explanatory.
FIDDLE
function textSpliter() {
var input = document.getElementById("inputText").value;
var names = input.split(",");
var groupSize = document.getElementById("groupNumber").value;
var groupCount = Math.ceil(names.length / groupSize);
var groups = [];
for (var i = 0; i < groupCount; i++) {
var group = [];
for (var j = 0; j < groupSize; j++) {
var random = Math.floor(Math.random() * names.length);
var name = names[random];
if (name != undefined) {
group.push(name);
names.splice(names.indexOf(name), 1);
}
}
group.sort();
groups.push(group);
}
printGroups(groups);
}
function printGroups(group) {
var output = document.getElementById("resInput");
output.value = "";
for (var i = 0; i < group.length; i++) {
var currentGroup = "";
for (var j = 0; j < group[i].length; j++) {
currentGroup = group[i].join(",");
}
output.value += currentGroup + "\r";
}
}
ES6 version ;-)
http://jsfiddle.net/dLgpny5z/1/
function textSpliter() {
var input = document.getElementById("inputText").value;
var names = input.replace(/\s*,\s*|\n/g, ",").split(",");
var groupSize = document.getElementById("groupNumber").value;
var groupCount = Math.ceil(names.length / groupSize);
var groups = [...Array(groupCount)].map(() => Array());
var i = 0
while (names.length > 0) {
var m = Math.floor(Math.random() * names.length);
groups[i].push(names[m]);
names.splice(m, 1);
i = (i >= groupCount - 1) ? 0 : i + 1
}
printGroups(groups);
}
function printGroups(groups) {
var output = document.getElementById("resInput");
output.value = groups.map(group => group.join(',')).join('\r');
}

Categories