Code to get last 2 items from an array - javascript

Am trying to get last 2 items from an array
result.forEach(function (re) {
console.log(re.files)
// prints ["utilities.rb", "print_utilities.rb", "lities.rb", "agination.rb"]
});
i only want to last two elements in the array in the order
[ "agination.rb", "print_utilities.rb"]
How it is possible

Use the Array.prototype.slice method for this with a negative index.
From MDN:
As a negative index, begin indicates an offset from the end of the
sequence. slice(-2) extracts the last two elements in the sequence.
slice returns a new array, so you can store the result in a new variable.
So in your case, simply use:
var arrayWithLast2Items = re.files.slice(-2);

jquery provides a slice method for this
e.g
$([1,2,3]).slice(-2)
https://api.jquery.com/slice/

Have a temp array with size 2, iterate the elements of original array and over write/copy elements to the temp array.
Once iteration is complete, the temp array will contain last 2 elements of original array.

Related

Taking a string and diving it into a array given an regex

I have the following structure, either a single string array ['stufff sjktasjtjser ((matchthis))'], or the same structure in a nested array ['stufff', ['more stuff ((matchhere))'], '((andanother))'];
I can loop and match all regex in the brackets and even replace the text:
//after flattening the array lets take the first one, assume I am looping in the first element.
var matches = currentArrayElement.matchAll('fancyregex') //pretend I am matching the brackets
matchs.forEach(match=>currentArrayElement=currentArrayElement.replaceAll(match[0],'whatwhat'))
console.log(currentArrayElement)//'stufff sjktasjtjser whatwhat'
//but what I actually want is
// currentArrayElement = ['stufff sjktasjtjser','whatwhat'];
Does anyone knows how I can achieve that? Or any template lib that can do that within nested arrays? I need to output sometimes an array of a string ['tss'] and sometimes an array with an object [{}].
Thanks.
The issue was that I needed to change the array in that index not the entire array.
Here is what I did then:
//after flattening the array lets take the first one, assume I am looping in the first element.
var matches = currentArrayElement.matchAll('fancyregex') //pretend I am matching the brackets
matches.forEach((match) => {
currentArrayElement[i] = c.split(match[0]).flatMap(
(value, index, array) => (array.length - 1 !== index
? [value, 'whatwhat',]
: value),
);
});

How does this line " return fileNameParts[fileNameParts.length-1]; " work?

function getFileExtension(i) {
if (i.indexOf(".") < 0) {
return false;
}
var filenameParts = i.split(".");
return filenameParts[filenameParts.length-1];
}
Here's the whole code. I understand it all except for the last line. I know what it does, but I don't know how or why. The second to last line splits the string at the ".", and then how does the last line actually get all the letters on the right side of the string?
By calling var filenameParts = i.split("."); an array is created containing the different parts. Imagine we use the filename test.txt and we use that string to split, we'll get an array like so:
filenameParts = ["test", "txt"]
Because the index of the first item in an array is 0, and we need the last item in the array, we call filenameParts.length-1 to get to the last item.
More information about javascript arrays can be found here.
The .split() function returns an array of strings, not a string. The expression filenameParts[filenameParts - 1] fetches the last element of the array.
filenameParts.length delivers the count of the filenameparts, split in the line above. filenameParts[number] delivers the one item of the array, which is positioned at number. -1 because arrays start at 0 not at 1. So it delivers the last item of the array. Clear?
filenameParts is an array and you read a single value with it's index. A value in this case is one part of the string between the ".".
filenameParts.length is equal to the count of values inside the array. As an array index starts with 0 you have to subtract 1 to get the index of the last value.
It looks like your function getFileExtension is designed to return the file extension of a given file. For example getFileExtension('image.gif') would return gif.
In the line (given that i is set to image.gif):
var filenameParts = i.split(".");
filenameParts will be an array, where image.gif has been split on the period. So filenameParts = ['image', 'gif'] where element zero is image and element one is gif. Remember that array indices are zero-based!
In the last line:
return filenameParts[filenameParts.length-1];
the function itself will return the last element in the filenameParts array (['image', 'gif']) which is gif. The part filenameParts.length-1 says get the length of the filenameParts array (which is 2), subtract 1 (which is 1), and return that element of the filenameParts array. So we return filenameParts[1] which is the last element of the array (remember, array indices are zero-based).
To get the last element of the array we could also have done
return filenameParts.pop();
because the pop() function returns the last element of an array.
var filenameParts = i.split('.') returns an array of made of the splitted elements of i
filenameParts[filenameParts.length-1];
select the last element of that array

JS Slice only removes Items when they were in the Constructor

I try to remove the first Item so that all other move up in an Array I create with
..
Queue: [],
..
and dynamically push Items into.
I later use slice to remove them and have then next Item be the first one.
..
thread.Queue.slice(0, 1);
..
It should return the first Item of the Array, which it does, but it should also remove it from the array and move all other up.
Here is a example which shows, that is neither working in the Browser. (I found this 'behaviour' in Node.js)
http://jsfiddle.net/bTrsE/
or rather
http://gyazo.com/b3dcdbf4f74642c04fe1c1025f225a08.png
Array.Slice = Is an implementation of SubArray, From an array you want to extract certain elements from the index and return a new array.
Example:
var cars = ['Nissan','Honda','Toyota'];
var bestCars = cars.splice(0,1);
console.log(bestCars);
//This should output Nissan Because i like Nissan
For your problem you should be looking Array.Splice(), splice adds / removes an element from the index
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
The .slice() method does not alter the original array. It returns a shallow copy of the portion of the array you asked for.

How does this snippet for removing duplicates from an array work

Regarding this post (Remove Duplicates from JavaScript Array) on creating a new array of unique values from another array.
Code in question:
uniqueArray = myArray.filter(function(elem, pos) {
return myArray.indexOf(elem) == pos;
})
Using this as the test data:
var names = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"];
Desired result is an array with only unique values:
var unique_names = ["Mike","Matt","Nancy","Adam","Jenny","Carl"];
Where I'm at:
I understand that filter will run a function on each member of the array, and that elem is the element being reviewed, and that pos is its index. If something causes that function to return false, then that element will not be included in the new array. So walking through it, this happens:
Is myArray.indexOf("Mike") the same as 0? Yes, so add "Mike" to the new array.
Is myArray.indexOf("Matt") the same as 1? Yes, so add "Matt" to the new array.
Is myArray.indexOf("Nancy") the same as 2? Yes, so add "Nancy" to the new array.
[repeat for all elements. All pass.]
Basically I don't get why the 2nd Nancy would evaluate to false.
The indexof is the index of the first appearance of the element, so the second Nancy would get the index of the first Nancy, and would be filtered out.
6) Is myArray.indexOf("Nancy") the same as 5? No (it's 2, just like it step 3), so skip the duplicated "Nancy".
indexOf gives you the first occurrence of the item.

Remove element from array, using slice

I am trying to remove a element from my array using slice, but i can't get it to work, look at this piece of code.
console.log(this.activeEffects); // Prints my array
console.log(this.activeEffects.slice(0,1)); // Remove from index 0, and remove one.
console.log(this.activeEffects); // Prints array again, this time my element should be gone
Result of this is.
So what is get from this is, at first the array is whole, as it should be. Then its prints what is sliced of the array. Finally the third should be empty? or?
function removeItemWithSlice(index) {
return [...items.slice(0, index), ...items.slice(index + 1)]
}
Slice will create a new array. We create two arrays: from beggining to index and from index+1 to end. Then we apply the spread operator (...) to take the items of those arrays and create a new single array containing all the items we care. I will paste an equivalent way if you don't like the one liner:
function removeItemWithSlice(index) {
const firstArr = items.slice(0, index);
const secondArr = items.slice(index + 1);
return [...firstArr , ...secondArr]
}
I believe you're looking for splice. From W3 Schools:
The splice() method adds/removes items to/from an array, and returns the removed item(s).
Take a look at the example on that page; the use case there is similar to what you want to achieve.
EDIT: Alternative link to MDN, as suggested by Nicosunshine; much more information about the command there.
a.slice(0, index).concat(a.slice(index + 1))
.slice does not mutate the array, you could use .splice() to remove the item at index i in the array:
this.activeEffects.splice(i, 1)
This is what I was able to come up with :
var newArray = oldArray.slice(indexOfElementToRemove+1).concat(oldArray.slice(0,indexOfElementToRemove));
Array.prototype.slice()...
does not alter the original array, but returns a new "one level
deep" copy that contains copies of the elements sliced from the
original array. Elements of the original array are copied into the new
array as follows:
Whereas Array.prototype.splice()...
Changes the content of an array, adding new elements while removing old elements.
This example should illustrate the difference.
// sample array
var list = ["a","b","c","d"];
// slice returns a new array
console.log("copied items: %o", list.slice(2));
// but leaves list itself unchanged
console.log("list: %o", list);
// splice modifies the array and returns a list of the removed items
console.log("removed items: %o", list.splice(2));
// list has changed
console.log("list: %o", list);
Look at here :
http://www.w3schools.com/jsref/jsref_slice_array.asp
You can see that the slice method select object et throw them into a new array object ^^ So you can't delete an object like this, may be you can try a thing like this :
var a = ["a","b","c"]; (pseudo code)
/* I wan't to remove the "b" object */
var result = a.slice(0,1)+a.slice(2,1); /* If you considers that "+" is a concatenation operator, i don't remember if it is true... */

Categories