Here's is an array with 5 elements 2.1.2 :001 > arr = ["a", "b", "c", "d", "e"] => ["a", "b", "c", "d", "e"] Lets look at few different cases Insert a new element at starting position Using unshift 2.1.2 :002 > arr.unshift("f") => ["f", "a", "b", "c", "d", "e"] Using insert 2.1.2 :005 > arr.insert(0, "f") => ["f", "a", "b", "c", "d", "e"] In the above example 0 is the position(index) Move existing element from one position to another The element in this case is "e" Using uniq to show only unique elements 2.1.2 :009 > arr.insert(0, "e").uniq => ["e", "a", "b", "c", "d"] With uniq we are only showing unique records but the element is listed
In JavaScript, you may combine the indexOf() method and the filter() method to get rid of duplicates from an array function removeDuplicates(arr) { return arr.filter((el, index) => arr.indexOf(el) === index); } let numbers = [1, 2, 3, 3, 4, 4, 5]; let uniqueNumbers = removeDuplicates(numbers); console.log(uniqueNumbers); // [1, 2, 3, 4, 5] The removeDuplicates() function in this code accepts an array as an argument and produces a new array that is empty of duplicates. This is accomplished by creating a new array with the filter() method that only contains elements that are unique within the original array. A callback function is provided as an argument to the filter() method, which is used to filter each element of the array. By comparing the current element's index to the output of executing indexOf() on the original array, the callback function determines if the current element exists only once in the array. The element is added to the new array if the two indices a
First, you need to open the file. Since the file is binary, you have to open it with an additional “b” flag. Here i am sending a zip file f = File.open("path/myzip.zip", "rb") Next, you have to do binary-to-text encoding on the binary file because the JSON will complain if you try to feed it a binary string. To overcome this obstacle, you need to apply Base64 encoding. file_content = Base64.b64encode(f.read()) After you have a text representation of the data, you can then use JSON to package it, you can use to_json to convert in to json {:file=>file_content}.to_json In your Rails application you can do this like render :layout=>false , :json => {:file=> file_content}.to_json
Comments
Post a Comment