Reverse a list of characters - javascript

list = [c,a,r,p,e,t]
function reverse(list) {
var i =0; j= list.length-1;
while(i < j) {
var temp = list[i];
list[i] = list[j];
list[j] = temp;
i++;
j--;
}
return list;
}
Hello everyone, I am trying to solve the problem above. It works for an array of numbers. How can I adapt it to handle a list of characters?

Arrays can be reversed by design natively without the needs of a loop:
var list = ['c','a','r','p','e','t'];
var reversedList = list.slice(0).reverse();
Check the Mozilla Developer Network: Array.prototype.reverse() and Mozilla Developer Network: Array.prototype.slice() for more infomation.

just use .reverse(); and assuming c,a,r,p,e,t is a variable then use String() if you want to sort it by letter and use Number() if sort it by number.
sort by string:
var list = [String(c),String(a),String(r),String(p),String(e),String(t)].reverse();
sort by number:
var list = [Number(c),Number(a),Number(r),Number(p),Number(e),Number(t)].reverse();
Reference: .reverse() String() Number()

Your code throws - Uncaught ReferenceError: c is not defined. As you miss to place " or ' along with character.
Change your step array declaration step :
From : list = [c,a,r,p,e,t]
To : list = ['c','a','r','p','e','t'] or list = ["c","a","r","p","e","t"]
Your working code
var list = ['c','a','r','p','e','t'];
function reverse(list) {
var i =0; j= list.length-1;
while(i < j) {
var temp = list[i];
list[i] = list[j];
list[j] = temp;
i++;
j--;
}
return list;
}
//Call the method;
reverse(list);
jsfiddle working example :
https://jsfiddle.net/m6kt3eus/1/
Other simpler way to achieve this :
The simple way to reverse the array is reverse() in javascript
Following are the example code snippet:
var list = ['c','a','r','p','e','t'];
list.reverse();
console.log(list);
arr.reverse() is used for in place reversal of the array. The first element of the array becomes the last element and vice versa.
Syntax:
arr.reverse()
Argument
This function does not take any argument.
Return value
This function returns the reference of the reversed original array.

function reverse(list) {
var list2 = [];
for (let i = 0; i < list.length; i++)
list2.unshift(list[i]);
return list2;
}
var list = ['c', 'a', 'r', 'p', 'e', 't'];
console.log(reverse(list));

Related

Add sums of array. Display one output

Update: The answer to this question is bellow. Thanks to dougtesting on a different thread. add array together, display sum
function hello() {
var arr = [];
for (var i = 0; i < 10; i++) {
arr.push(prompt('Enter number' + (i+1)));
}
var total = 0;
for(i=0; i<arr.length; i++) {
var number = parseInt(arr[i], 10);
total += number;
}
console.log(total);
}
//End of answer.
I am trying to have a user input 10 numbers. Then add those numbers together and display the output to the user. I was able to get the amount of inputs (10) into a array but I can't get arrays contents. I feel like I'm missing something simple. Would you mind taking a look?
// https://stackoverflow.com/questions/28252888/javascript-how-to-save-prompt-input-into-array
var arr = []; // define our array
for (var i = 0; i < 10; i++) { // loop 10 times
arr.push(prompt('Enter number' + (i+1))); // push the value into the array
}
alert('Full array: ' + arr.join(', ')); // alert the result
var arrEquals = []; //Empty Arr
arrEquals = arr.push(); //turn string into var
alert (arrEquals);//show string to admin for debug
//(for loop) console out # of array elements. does not output what is in array
//this is half the battle
for (var a = 0; a < arrEquals; a++){
var a = Number(a); //ensure input is Number()
console.log(a + "A"); //used for debug
}
//taks sums in array and adds them together
//this is the other half of the problem
// https://www.w3schools.com/jsref/jsref_forEach.asp
// var sum = 0;
// var numbers = [65, 44, 12, 4];
// function myFunction(item) {
// sum += item;
// demo.innerHTML = sum;
// }
This is probably one of the simplest examples of something that Javascript's built in array .reduce() function would be used for. Effectively, you're "reducing an array to a single value".
A reduce works by taking an array and running a function on each item. This "callback" function receives the value that the previous function returns, processes it in some way, then returns a new value. Worth noting, the reduce function also takes a 2nd argument that acts as the initial value that will be passed to the callback function the first time.
array.reduce(callbackFunction, initialValue);
Here's an example of reduce being used to sum an array.
var result = [1,2,3,4,5,6,7,8,9,10].reduce(function(accumulator, currentValue) {
return accumulator + currentValue;
}, 0); // start with an initial value of 0
console.log(result);
Using ES6 syntax, this can be further simplified to a one-liner
var result = [1,2,3,4,5,6,7,8,9,10].reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(result);
In your loop you're referencing arrEquals like for (var a = 0; a < arrEquals; a++){. you need to reference it like for (var a = 0; a < arrEquals.length; a++){ because just referencing the array doesn't tell javascript how long it is, or what number to count to. the .length returns a number, that number is how many items are in the array.
var arr = []; // define our array
for (var i = 0; i < 10; i++) { // loop 10 times
arr.push(prompt('Enter number' + (i+1))); // push the value into the array
}
arr = arr.join(', ');
alert('Full array: ' + arr); // alert the result
var arrEquals = []; //Empty array
arrEquals.push(arr); //assign arr string to an empty array
alert (arrEquals[0]); //show array[0] string to admin for debug
Is this what you are looking for? You need to put the arr.join() result to a variable, like itself.
You shouldnt be using arr.push() at all if you're not pushing new array items on it
//(for loop) console out # of array elements. does not output what is in array
//this is half the battle
for (var a = 0; a < arrEquals.length; a++){
//a is always a int in this case
console.log(a + "A"); //used for debug
}

Remove an item from a copy of an array without removing it from the original array

How can I remove an object from a copy of an array without removing it from the original?
I have a global variable :
var userTrickList = [];
And inside a function, I make a copy of that global array :
var tempUserTrickList = userTrickList;
Then I use the removeItem function that I created to remove a certain object.
removeItem(considerTrick.IDName, tempUserTrickList);
function removeItem(item, list) {
//takes a string as 'item', finds in the array as 'list',
//then removes it from the list.
for(var i = 0; i < list.length; i++)
{
if(item === list[i])
{
list.splice(i,1);
}
}
}
My problem is, this function removes it from the userTrickList too.
Any ideas? It's definitely a problem in "removeItem(considerTrick.IDName, tempUserTrickList);", but I can't think of a solution.
Use .slice(0) to clone an array.
var tempUserTrickList = userTrickList.slice(0);
Credits:
http://davidwalsh.name/javascript-clone-array
use this function for your requirement
function removeElementFromArray(data,target) {
var temp=new Array();
for ( var i = 0; i < data.length; i++) {
if(data[i]!=target){
temp.push(data[i]);
}
}
return temp; }
here data is original array and target is the element you want to remove from array
this function will return array without containing the removed item.
Try, It copy the original array
var tempUserTrickList = JSON.parse(JSON.stringify(userTrickList));
Demo CopyArray
for (i = 0, l = arr.length; i < l; i++) {
if (arr[i] === item) {
arr.splice(i, 1);
i -= 1;
l -= 1;
}
}
Daniel's method of cloning an array is absolutely correct, but since I don't see an ES6-oriented answer, I'll offer up an alternative solution:
We can just as easily use the spread operator to clone an array, so we don't have to use the slice call.
const arr = [1, 2, 3];
const copy = [...arr];
copy.pop();
console.log(arr); // returns [1, 2, 3]
console.log(copy); // returns [1, 2]

jQuery iterate through loop delete elements

I have a javascript array of objects: each object contains key/value pairs. I'm trying to iterate through this array, and delete any object whose value for a particular key (say "Industry") fails to match a given value. Here is my code, for some reason it's not looping through the whole array, and I think it has something to do with the fact that when I delete an item the loop counter is botched somehow:
var industry = 'testing';
var i = 0;
for (i = 0; i < assets_results.length; i++) {
var asset = assets_results[i];
var asset_industry = asset['industry'];
if (industry != asset_industry) { assets_results.splice(i,1); }
}
Any ideas? Thanks in advance.
This is because when you splice one element, the size of array decreases by one. All elements after the splice shift one position to the beginning of the array and fills the space of spliced one. So the code misses one element.Try this code.
var industry = 'testing';
var i = 0;
for (i = 0; i < assets_results.length; i++) {
var asset = assets_results[i];
var asset_industry = asset['industry'];
if (industry != asset_industry) {
assets_results.splice(i,1);
i--;
}
}
This is a common problem when modifying an object while iterating through it. The best way to avoid this problem is, rather than deleting pairs from the existing array if they fail the test, to create a new array and only add pairs if they pass the test.
var industry = 'testing';
var i = 0;
var asset_results_filtered = [];
for (i = 0; i < assets_results.length; i++) {
if (industry == assets_results[i]) {
asset_results_filtered.push(assets_results[i]);
}
}
EDIT: Your code looked a bit illogical — I modified the example to use the variables given.
splice removes an element from an array and resizes it :
var arra = ['A', 'B', 'C', 'D'];
arr.splice(1,2); // -> ['A', 'D'];
Which means that you should not increment i when you splice, because you skip the next element. splicing will make of the i + 2 element the i + 1 element.
var industry = 'testing';
for (var i = 0, max = assets_results.length; i < max; ) { // Accessing a property is expensive.
if (industry != assets_results[i]['industry']) {
assets_results.splice(i,1);
} else {
++i;
}
}
Try this instead:
var industry = 'testing';
var i = assets_results.length - 1;
for (; i > 0; i--) {
var asset = assets_results[i],
asset_industry = asset['industry'];
if (industry != asset_industry) { assets_results.splice(i,1); }
}

Count how many strings in an array have duplicates in the same array [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Array value count javascript
I have an array which contains several duplicates, what I'm trying to achieve is to count how many duplicates each unique string has in this one array.
The array looks something like this
array = ['aa','bb','cc','aa','ss','aa','bb'];
Thus I would like to do something like this
if (xWordOccurrences >= 5) {
// do something
}
But I'm not sure how I would code this.
I was thinking, create an object with each unique string, then loop through the original array, match each string with it's object and increment it's number by 1, then loop over the object to see which words had the most duplicates...
But this seems like an over complexe way to do it.
You can use an object which has keys of the Array's values and do something like this
// count everything
function getCounts(arr) {
var i = arr.length, // var to loop over
obj = {}; // obj to store results
while (i) obj[arr[--i]] = (obj[arr[i]] || 0) + 1; // count occurrences
return obj;
}
// get specific from everything
function getCount(word, arr) {
return getCounts(arr)[word] || 0;
}
getCount('aa', ['aa','bb','cc','aa','ss','aa','bb']);
// 3
If you only ever want to get one, then it'd be more a bit more efficient to use a modified version of getCounts which looks similar to getCount, I'll call it getCount2
function getCount2(word, arr) {
var i = arr.length, // var to loop over
j = 0; // number of hits
while (i) if (arr[--i] === word) ++j; // count occurance
return j;
}
getCount2('aa', ['aa','bb','cc','aa','ss','aa','bb']);
// 3
Try this function:
var countOccurrences = function(arr,value){
var len = arr.length;
var occur = 0;
for(var i=0;i<len;i++){
if(arr[i]===value){
occur++;
}
}
return occur;
}
var count = countOccurrences(['aaa','bbb','ccc','bbb','ddd'],'bbb'); //2
If you want, you can also add this function to the Array prototype:
Array.prototype.countOccurrences = function(value){
var len = this.length;
var occur = 0;
for(var i=0;i<len;i++){
if(this[i]===value){
occur++;
}
}
return occur;
}
How about you build an object with named property?
var array = ['aa','bb','cc','aa','ss','aa','bb'];
var summary = {};
var item = '';
for ( i in array){
item = array[i];
if(summary[item]){
summary[item] += 1;
}
else{
summary[item] = 1;
}
}
console.log( summary );
summary will contain like this
{aa: 3, bb: 2, cc: 1, ss: 1}
which you could then iterate on and then sort them later on if needed.
finally to get your count, you could use this summary['aa']
<script type="text/javascript">
var array = ['aa','bb','cc','aa','ss','aa','bb'];
var myMap = {};
for(i = 0; i < array.length; i++) {
var count = myMap[array[i]];
if(count != null) {
count++;
} else {
count = 1;
}
myMap[array[i]] = count;
}
// at this point in the script, the map now contains each unique array item and a count of its entries
</script>
Hope this solves your problem
var array = ['aa','bb','cc','aa','ss','aa','bb'];
var dups = {};
for (var i = 0, l = array.length; i < l; i++ ) {
dups[array[i]] = [];
}
for (str in dups) {
for (var i = 0, l = array.length; i < l; i++ ) {
if (str === array[i]) {
dups[str].push(str);
}
}
}
for (str in dups) {
console.log(str + ' has ' + (dups[str].length - 1) + ' duplicate(s)');
}
This function may do everything you need.
function countDupStr(arr, specifier) {
var count = {}, total = 0;
arr.forEach(function (v) {
count[v] = (count[v] || 0) + 1;
});
if(typeof specifier !== 'undefined') {
return count[specifier] - 1;
}
Object.keys(count).forEach(function (k) {
total += count[k] - 1;
});
return total;
}
Each value in the array is assigned and incremented to the count object. Whether or not a specifier was passed, the function will return duplicates of that specific string or the total number of duplicates. Note that this particular technique will only work on string-coercible values inside your arrays, as Javascript can only index objects by string.
What this means is that during object assignment, the keys will normalize down to strings and cannot be relied upon for uniqueness. That is to say, this function wouldn't be able to discern the difference between duplicates of 3 and '3'. To give an example, if I were to perform:
var o = {}, t = {};
o[t] = 1;
console.log(o);
The key used in place of t would eventually be t.toString(), thus resulting in the perhaps surprising object of {'[object Object]': 1}. Just something to keep in mind when working with Javascript properties.
I saw this post about it, perhaps it can help:
http://ryanbosinger.com/blog/2011/javascript-count-duplicates-in-an-array/

How to find unique records from two different array in jquery or javascript?

I want to get unique values from two different arrays.
Two arrays are as below in JavaScript:
<script>
var a=new Array;
var b=new Array;
a={'a','b','c','d','e'}
b={'a','d','e','c'}
</script>
I want output like:
new array => {'a','c','d','e'}
How can I find unique records from both arrays using JavaScript prototype function or jQuery function?
I don't know if you have the terms correct. Unique values to me would be members which appear only once in either array. It seems you want members that are present in both arrays (common values, or intersection), based on your example.
You can use jQuery to handle this. grep() is your friend.
You could do this without jQuery, but I'm not sure if the native filter() and indexOf() methods have the best browser support.
var a = ['a', 'b', 'c', 'd', 'e'],
b = ['a', 'd', 'e', 'c'];
var common = $.grep(a, function(element) {
return $.inArray(element, b) !== -1;
});
console.log(common); // ["a", "c", "d", "e"]
With underscore it's easy at _.intersection(arr1, arr2).
jsFiddle.
I think you really meant to write:
<script type="text/javascript">
var a = ['a','b','c','d','e'];
var b = ['a','d','e','c'];
</script>
In any case, you can sort the arrays and get the values from one that aren't in the other and vice versa, then concatenate the two sets into one. You seem spoilt for choice, so here's a nice basic javascript version that should work in most browsers. Using new features of the latest browsers is certain to fail in older browsers.
// Compares a to b. Returns all the elements in a that are not in b
// If c provided, add unique elements to c
function getUnique(a, b, c) {
var c = c || [];
var ta = a.slice().sort();
var tb = b.slice().sort();
var x, y, found = false;
for (var i=0, iLen=ta.length; i<iLen; i++) {
x = ta.shift();
for (var j=0; j<tb.length && !found; j++) { // j.length changes each loop
if (tb[j] == x) {
tb.splice(j,1); // Remove match from b
found = true;
}
}
if (!found) {
c.push(x); // If no match found, store in result
}
found = false;
}
return c;
}
var a = ['a','b','d'];
var b = ['b','e'];
var d = getUnique(a, b);
alert(d);
var c = getUnique(b,a,d);
alert(d);
But your comment on the first answer indicates that you want the elements that are common to both arrays, which is simpler:
function getCommon(a, b) {
var c = [];
var ta = a.slice().sort();
var tb = b.slice().sort();
var t, found;
for (var i=0, iLen=ta.length; i<iLen; i++) {
t = ta[i];
found = false;
for (var j=0, jLen=tb.length; j<jLen && !found; j++) {
if (t == tb[j]) {
c.push(tb.splice(j,1));
found = true;
}
}
}
return c;
}
alert(getCommon(a, b));
You need to work out what to do with duplicates. In the first case, a duplicates will be treated as unique if there isn't a duplicate in the other array. In the above, duplicates don't matter unless they are duplicated in both arrays.
Find orignal answer : JavaScript array difference
You could use a Set in this case. It is optimized for this kind of operation (union, intersection, difference).
Make sure it applies to your case, once it allows no duplicates.
var a = new JS.Set([1,2,3,4,5,6,7,8,9]);
var b = new JS.Set([2,4,6,8]);
a.intersection(b);//intersect will give you the common one
Like this:
var a=['a','b','c','d','e']; //Use brackets
var b=['a','d','e','c']
var c = a.concat(b).sort();
var uniques = {};
for(var i=0; i<c.length; i++){
uniques[c[i]] = true;
}
var uniquesArray = [];
for(var u in uniques)
uniquesArray.push(u)
Now uniquesArray contains only unique values.
Hope this Helps
I would like to do this operation with the help of associative array support in JavaScript.
<script>
var a=new Array;
var b=new Array;
a={'a','b','c','d','e'}
b={'a','d','e','c'}
var uniqueArray = new Array;
var tempArray = new Array;
var j = 0;
for(var i = 0; i < a.length; i++) {
if(!tempArray[a[i]]) {
tempArray[a[i]] = true;
uniqueArray[j++] = a[i];
}
}
for(i = 0; i < b.length; i++) {
if(!tempArray[b[i]]) {
tempArray[b[i]] = true;
uniqueArray[j++] = b[i];
}
}
</script>

Categories